4196 results

namespace LobbySystem;

/// <summary>
/// Auto-hosts a lobby so Steam friends can join, and keeps one networked pawn per connection plus optional
/// bots by cloning <see cref="PlayerPrefab"/>. The pawn only has to implement <see cref="ILobbyAgent"/>.
/// Spawning is de-duped and runs in OnUpdate so a join can't fire mid-enumeration.
/// </summary>
public sealed class LobbyNetworkManager : Component, Component.INetworkListener
{
	[Property] public GameObject PlayerPrefab { get; set; }
	[Property] public int BotCount { get; set; } = 1;

	/// <summary>When true, bots only exist during an active round.</summary>
	[Property] public bool BotsOnlyDuringRound { get; set; } = true;

	[Property] public Color BotTint { get; set; } = new Color( 1f, 0.35f, 0.3f );

	// Lobby spawn ring, used before a round map loads.
	readonly Vector3[] _spawns =
	{
		new Vector3( 0f, -300f, 40f ), new Vector3( 300f, 0f, 40f ),
		new Vector3( 0f, 300f, 40f ),  new Vector3( -300f, 0f, 40f ),
		new Vector3( 250f, 250f, 40f ), new Vector3( -250f, -250f, 40f ),
	};
	int _spawnIndex;
	readonly Dictionary<Guid, GameObject> _pawns = new();
	readonly List<GameObject> _bots = new();

	bool _reconcileNow;
	TimeUntil _nextReconcile;
	TimeUntil _nextSweep;

	protected override async Task OnLoad()
	{
		// When joining a friend the engine is mid-connect and IsActive is briefly false, so poll for a
		// moment before hosting. Otherwise a joiner would spin up its own solo lobby.
		if ( Networking.IsActive ) return;
		for ( int i = 0; i < 6 && !Networking.IsActive; i++ )
			await Task.DelayRealtimeSeconds( 0.1f );
		if ( !Networking.IsActive )
			Networking.CreateLobby( new() );
	}

	void INetworkListener.OnActive( Connection channel ) => _reconcileNow = true;

	protected override void OnUpdate()
	{
		if ( !Networking.IsHost || PlayerPrefab is null ) return;

		if ( !_reconcileNow && _nextReconcile > 0f ) return;
		_reconcileNow = false;
		_nextReconcile = 0.25f;

		try
		{
			bool wantBots = !BotsOnlyDuringRound || (LobbyDirector.Current?.State == LobbyState.Active);
			ReconcileBots( wantBots ? Math.Max( 0, BotCount ) : 0 );

			foreach ( var conn in Connection.All.ToList() )
			{
				if ( conn is null || !conn.IsActive ) continue;
				if ( _pawns.TryGetValue( conn.Id, out var pawn ) && pawn.IsValid() ) continue;
				var id = conn.Id;
				_pawns[id] = FindConnectionPawn( id ) ?? SpawnPawn( false, conn.DisplayName, conn );
			}

			Sweep();
		}
		catch
		{
			// Connection or scene list changed during the pass; retry next frame.
		}
	}

	void ReconcileBots( int target )
	{
		_bots.RemoveAll( b => !b.IsValid() );
		while ( _bots.Count > target )
		{
			var b = _bots[_bots.Count - 1];
			_bots.RemoveAt( _bots.Count - 1 );
			if ( b.IsValid() ) b.Destroy();
		}
		while ( _bots.Count < target )
			_bots.Add( SpawnPawn( true, "Bot", null ) );
	}

	GameObject FindConnectionPawn( Guid id )
	{
		foreach ( var a in Scene.GetAllComponents<ILobbyAgent>() )
		{
			if ( !a.IsValid() || a.IsBot ) continue;
			if ( a is Component c && c.Network.OwnerId == id ) return c.GameObject;
		}
		return null;
	}

	void Sweep()
	{
		if ( _nextSweep > 0f ) return;
		_nextSweep = 1f;
		foreach ( var key in _pawns.Where( kv => !kv.Value.IsValid() ).Select( kv => kv.Key ).ToList() )
			_pawns.Remove( key );
	}

	GameObject SpawnPawn( bool isBot, string displayName, Connection owner )
	{
		var go = PlayerPrefab.Clone( NextSpawn() );
		go.Name = isBot ? "Bot" : $"Player - {displayName}";
		go.Enabled = true;

		var agent = go.Components.Get<ILobbyAgent>() ?? go.Components.GetInChildren<ILobbyAgent>();
		agent?.InitAgent( isBot, displayName );

		if ( isBot )
		{
			var rend = go.Components.GetInChildren<SkinnedModelRenderer>();
			if ( rend is not null ) rend.Tint = BotTint;
		}

		if ( owner is not null ) go.NetworkSpawn( owner );
		else go.NetworkSpawn();
		return go;
	}

	Vector3 NextSpawn()
	{
		int idx = _spawnIndex++;
		var dir = LobbyDirector.Current;
		if ( dir is not null && dir.UseRoundMap && dir.MapReady )
			return dir.RoundSpawnPoint( idx );
		return _spawns[idx % _spawns.Length];
	}
}
namespace LobbySystem;

/// <summary>Lifecycle of the lobby: Lobby, then Active, then Ended before looping back.</summary>
public enum LobbyState
{
	/// <summary>Free roam before and after a round. The mode button works here.</summary>
	Lobby,
	/// <summary>A round is running.</summary>
	Active,
	/// <summary>Round finished; results show before returning to the lobby.</summary>
	Ended
}
namespace LobbySystem;

/// <summary>
/// In-world button that opens the mode menu for the host, or a local suggestion menu for a client. It needs
/// a ModelRenderer to be visible and is hidden while a round is live. When the local player is within
/// <see cref="UseRange"/> and presses Use, the menu opens.
/// </summary>
public sealed class LobbyModeButton : Component
{
	[Property] public float UseRange { get; set; } = 130f;
	[Property] public bool GlowWhenInRange { get; set; } = true;
	[Property] public Color IdleTint { get; set; } = new Color( 0.85f, 0.4f, 0.15f );
	[Property] public Color ActiveTint { get; set; } = new Color( 1f, 0.85f, 0.3f );

	ModelRenderer _renderer;
	ILobbyAgent _me;

	protected override void OnStart()
	{
		_renderer = Components.Get<ModelRenderer>() ?? Components.GetInChildren<ModelRenderer>();
		if ( _renderer is not null ) _renderer.Tint = IdleTint;
	}

	protected override void OnUpdate()
	{
		var dir = LobbyDirector.Current;
		bool inLobby = dir is null || !dir.RoundLive;
		if ( _renderer is not null && _renderer.Enabled != inLobby )
			_renderer.Enabled = inLobby;
		if ( !inLobby ) return;

		var me = LocalPlayer();
		bool inRange = me is not null && WorldPosition.Distance( me.WorldPosition ) <= UseRange;

		if ( GlowWhenInRange && _renderer is not null )
			_renderer.Tint = inRange ? ActiveTint : IdleTint;

		if ( inRange && Input.Pressed( "Use" ) )
			dir?.RequestModeMenu();
	}

	ILobbyAgent LocalPlayer()
	{
		if ( _me is not null && _me.IsValid() && !_me.IsBot && !_me.IsProxy ) return _me;
		try { _me = Scene.GetAllComponents<ILobbyAgent>().FirstOrDefault( c => c.IsValid() && !c.IsBot && !c.IsProxy ); }
		catch { _me = null; }
		return _me;
	}
}
global using static Sandbox.Internal.GlobalGameNamespace;
global using Microsoft.AspNetCore.Components;
global using Microsoft.AspNetCore.Components.Rendering;
[assembly: global::System.Reflection.AssemblyMetadata( "AddonTitle", "MC Clouds" )]
[assembly: global::System.Reflection.AssemblyMetadata( "AddonIdent", "mcclouds" )]
[assembly: global::System.Reflection.AssemblyMetadata( "OrgIdent", "trend" )]
[assembly: global::System.Reflection.AssemblyMetadata( "Ident", "trend.mcclouds" )]
[assembly: global::System.Reflection.AssemblyMetadata( "EngineVersion", "26" )]
[assembly: global::System.Reflection.AssemblyMetadata( "EngineMinorVersion", "1" )]

[assembly: System.Runtime.Versioning.TargetFramework( ".NETCoreApp,Version=v9.0", FrameworkDisplayName = ".NET 9.0" )]
[assembly: global::System.Reflection.AssemblyMetadata( "CompileTime", "2026-06-16T17:04:05.4666731Z" )]
[assembly: global::System.Reflection.AssemblyVersion("0.0.124.0")]
[assembly: global::System.Reflection.AssemblyFileVersion("0.0.124.0")]
using Sandbox;
using Sandbox.UI;
using System;

namespace SbTween;

public static class LightExtensions
{

	public static BaseTween TweenLightColor( this Light Light, Color target, float duration )
	{
		Color start = Light.LightColor;
		var tween = new BaseTween( duration );
		tween.Target = Light.GameObject;
		return TweenManager.Instance.AddTween( tween
			.OnStart( () => start = Light.LightColor )
			.OnUpdate( p => Light.LightColor = Color.Lerp( start, target, p ) ) );
	}

	public static BaseTween TweenRadius( this SpotLight light, float target, float duration )
	{
		if ( !light.IsValid() ) return null;

		float start = light.Radius;
		return TweenManager.Instance.AddTween( new BaseTween( duration )
			.OnStart( () => start = light.Radius )
			.OnUpdate( p => light.Radius = MathX.Lerp( start, target, p ) ) );
	}

	public static BaseTween TweenConeOuter( this SpotLight light, float target, float duration )
	{
		if ( !light.IsValid() ) return null;

		float start = light.ConeOuter;
		return TweenManager.Instance.AddTween( new BaseTween( duration )
			.OnStart( () => start = light.ConeOuter )
			.OnUpdate( p => light.ConeOuter = MathX.Lerp( start, target, p ) ) );
	}

	public static BaseTween TweenInnerCone( this SpotLight light, float target, float duration )
	{
		if ( !light.IsValid() ) return null;

		float start = light.ConeInner;
		return TweenManager.Instance.AddTween( new BaseTween( duration )
			.OnStart( () => start = light.ConeInner )
			.OnUpdate( p => light.ConeInner = MathX.Lerp( start, target, p ) ) );
	}

	public static BaseTween TweenAttenuation( this PointLight light, float target, float duration )
	{
		if ( !light.IsValid() ) return null;

		float start = light.Attenuation;
		return TweenManager.Instance.AddTween( new BaseTween( duration )
			.OnStart( () => start = light.Attenuation )
			.OnUpdate( p => light.Attenuation = MathX.Lerp( start, target, p ) ) );
	}

	public static BaseTween TweenRadius( this PointLight light, float target, float duration )
	{
		if ( !light.IsValid() ) return null;

		float start = light.Radius;
		return TweenManager.Instance.AddTween( new BaseTween( duration )
			.OnStart( () => start = light.Radius )
			.OnUpdate( p => light.Radius = MathX.Lerp( start, target, p ) ) );
	}

	public static BaseTween TweenAttenuation( this SpotLight light, float target, float duration )
	{
		if ( !light.IsValid() ) return null;

		float start = light.Attenuation;
		return TweenManager.Instance.AddTween( new BaseTween( duration )
			.OnStart( () => start = light.Attenuation )
			.OnUpdate( p => light.Attenuation = MathX.Lerp( start, target, p ) ) );
	}

	//FLICKERING LIGHT
	public static BaseTween TweenFlickerLight( this PointLight light, float minBrightness, float maxBrightness, float duration, float speed = 10f )
	{
		if ( !light.IsValid() ) return null;

		float time = 0f;
		return TweenManager.Instance.AddTween( new BaseTween( duration )
			.OnUpdate( _ =>
			{
				time += Time.Delta * speed;
				float noise = MathF.Sin( time * 1.3f ) * MathF.Sin( time * 2.7f ) * MathF.Sin( time * 0.9f );
				float t = (noise + 1f) * 0.5f;
				light.Attenuation = MathX.Lerp( minBrightness, maxBrightness, t );
			} ) );
	}

	public static BaseTween TweenFlickerLight( this SpotLight light, float minBrightness, float maxBrightness, float duration, float speed = 10f )
	{
		if ( !light.IsValid() ) return null;

		float time = 0f;
		return TweenManager.Instance.AddTween( new BaseTween( duration )
			.OnUpdate( _ =>
			{
				time += Time.Delta * speed;
				float noise = MathF.Sin( time * 1.3f ) * MathF.Sin( time * 2.7f ) * MathF.Sin( time * 0.9f );
				float t = (noise + 1f) * 0.5f;
				light.Attenuation = MathX.Lerp( minBrightness, maxBrightness, t );
			} ) );
	}

	//FLICKERING Color

	public static BaseTween TweenFlickerColor( this PointLight light, Color colorA, Color colorB, float duration, float speed = 10f )
	{
		if ( !light.IsValid() ) return null;

		float time = 0f;
		return TweenManager.Instance.AddTween( new BaseTween( duration )
			.OnUpdate( _ =>
			{
				time += Time.Delta * speed;
				float noise = MathF.Sin( time * 1.3f ) * MathF.Sin( time * 2.7f ) * MathF.Sin( time * 0.9f );
				float t = (noise + 1f) * 0.5f;
				light.LightColor = Color.Lerp( colorA, colorB, t );
			} ) );
	}

	public static BaseTween TweenFlickerColor( this SpotLight light, Color colorA, Color colorB, float duration, float speed = 10f )
	{
		if ( !light.IsValid() ) return null;

		float time = 0f;
		return TweenManager.Instance.AddTween( new BaseTween( duration )
			.OnUpdate( _ =>
			{
				time += Time.Delta * speed;
				float noise = MathF.Sin( time * 1.3f ) * MathF.Sin( time * 2.7f ) * MathF.Sin( time * 0.9f );
				float t = (noise + 1f) * 0.5f;
				light.LightColor = Color.Lerp( colorA, colorB, t );
			} ) );
	}

}
using Sandbox;
using System;

namespace SbTween;

public static class AudioExtensions
{
	public static BaseTween TweenVolume( this SoundPointComponent sound, float targetVolume, float duration )
	{
		float startVolume = sound.Volume;
		var tween = new BaseTween( duration );
		tween.Target = sound.GameObject;

		return TweenManager.Instance.AddTween( tween
			.OnStart( () => startVolume = sound.Volume )
			.OnUpdate( p =>
			{
				if ( !sound.IsValid() ) return;
				sound.Volume = MathX.Lerp( startVolume, targetVolume, p );
			} )
		);
	}
	
	public static BaseTween TweenPitch( this SoundPointComponent sound, float targetPitch, float duration )
	{
		float startPitch = sound.Pitch;
		var tween = new BaseTween( duration );
		tween.Target = sound.GameObject;

		return TweenManager.Instance.AddTween( tween
			.OnStart( () => startPitch = sound.Pitch )
			.OnUpdate( p =>
			{
				if ( !sound.IsValid() ) return;
				sound.Pitch = MathX.Lerp( startPitch, targetPitch, p );
			} )
		);
	}
}
using Sandbox;
using System;

namespace SbTween;

public static class MathTweenExtensions
{
	public static BaseTween TweenInCircle( this GameObject obj, float duration, Vector3 axis, float range, float speed, bool snapping = false )
	{
		Vector3 centerPos = obj.WorldPosition;
		var tween = new BaseTween( duration );
		tween.Target = obj;

		Vector3 normal = axis.Normal;
		Vector3 v1 = Vector3.Cross( normal, MathF.Abs( normal.z ) < 0.9f ? Vector3.Up : Vector3.Forward ).Normal;
		Vector3 v2 = Vector3.Cross( normal, v1 ).Normal;

		return TweenManager.Instance.AddTween( tween
			.OnUpdate( p =>
			{
				if ( !obj.IsValid() ) return;

				float angleDegrees = p * 360f * speed;
				float angleRadians = angleDegrees * (MathF.PI / 180f);

				float cos = MathF.Cos( angleRadians ) * range;
				float sin = MathF.Sin( angleRadians ) * range;

				Vector3 rotatedOffset = (v1 * cos) + (v2 * sin);
				obj.WorldPosition = centerPos + rotatedOffset;
			} )
		);
	}

	public static BaseTween TweenSpiral( this GameObject obj, float duration, Vector3 axis, float speed, float frequency )
	{
		Vector3 startPos = obj.WorldPosition;
		var tween = new BaseTween( duration );
		tween.Target = obj;

		return TweenManager.Instance.AddTween( tween
			.OnStart( () => startPos = obj.WorldPosition )
			.OnUpdate( p =>
			{
				if ( !obj.IsValid() ) return;

				float angle = p * MathF.PI * 2f * frequency;

				float currentRadius = p * speed;

				float x = MathF.Cos( angle ) * currentRadius;
				float y = MathF.Sin( angle ) * currentRadius;

				Vector3 axisOffset = axis * p;

				Vector3 circleOffset = new Vector3( x, y, 0 );

				obj.WorldPosition = startPos + axisOffset + circleOffset;
			} )
		);
	}
	
	public static BaseTween TweenPunchFloat( this GameObject obj, float v, float amplitude, float duration, int vibrations = 5, float elasticity = 1f, Action<float> setter = null )
	{
		var tween = new BaseTween( duration );
		tween.Target = obj;

		return TweenManager.Instance.AddTween( tween
			.OnUpdate( p =>
			{
				if ( !obj.IsValid() ) return;
				if ( p >= 1.0f )
				{
					setter?.Invoke( v );
					return;
				}
				
				float decay = MathF.Pow( 1f - p, elasticity * 3f );

				float omega = vibrations * MathF.PI * 2f;
				float oscillation = MathF.Sin( p * omega );

				float currentOffset = amplitude * oscillation * decay;

				setter?.Invoke( v + currentOffset );
			} )
			.OnComplete( () => setter?.Invoke( v ) )
		);
	}
	
	public static BaseTween TweenShakeFloat( this GameObject obj, float baseline, float strength, float duration, Action<float> setter = null )
	{
		var tween = new BaseTween( duration );
		tween.Target = obj;

		return TweenManager.Instance.AddTween( tween
			.OnUpdate( p =>
			{
				if ( !obj.IsValid() ) return;
				if ( p >= 1.0f )
				{
					setter?.Invoke( baseline );
					return;
				}

				float currentStrength = strength * (1.0f - p);
             
				float randomOffset = Game.Random.Float( -currentStrength, currentStrength );

				setter?.Invoke( baseline + randomOffset );
			} )
			.OnComplete( () => setter?.Invoke( baseline ) )
		);
	}
}
namespace Sandbox.UiPro;

public enum HorizontalAlignment
{
	Left,
	Center,
	Right
}

public enum VerticalAlignment
{
	Top,
	Center,
	Bottom
}

[Title( "Text Node - UI Pro" ), Category( "UI Pro" ), Icon( "text_fields" )]
public class TextNode : NodeComponent
{
	[Property, InlineEditor, Group( "Layout Settings" ), Order( -999 )] public override NodeStyle Style { get; set; } = GetDefaultStyle();

	[Property, Group("Text Settings")] public HorizontalAlignment HorizontalAlignment { get; set; } = HorizontalAlignment.Center;
	[Property, Group( "Text Settings" )] public VerticalAlignment VerticalAlignment { get; set; } = VerticalAlignment.Center;
	[Property, InlineEditor, Group( "Text Settings" )] public TextRendering.Scope TextScope { get; set; } = TextRendering.Scope.Default;

	private static NodeStyle GetDefaultStyle()
	{
		return new NodeStyle()
		{
			Anchor = NodePoint.CenterMiddle,
			Pivot = NodePoint.CenterMiddle,
			Offset = Vector2.Zero,
			Size = new Vector2( 100, 100 ),
			ChildPadding = Vector2.Zero,
			ClipChildren = false,
			StretchHorizontal = false,
			StretchVertical = false,
			CornerRadius = 0,
			BorderWidth = 0,
			BorderColor = Color.Black,
			Texture = Texture.White,
			Tint = Color.White,
			UvScale = Vector2.One,
			UvOffset = Vector2.Zero
		};
	}

	protected override void UpdateStyle(float scaleFactor)
	{
		Style.BorderWidth = 0; // for debugging
		Style.BorderColor = Color.White;

		TextRendering.Scope scope = TextScope;
		scope.FontSize *= scaleFactor;

		Texture texture = TextRendering.GetOrCreateTexture( scope );
		Style.Texture = texture;

		Vector2 scale = (Layout.Outer.Size * scaleFactor) / texture.Size;
		Style.UvScale = scale;

		float alignX = HorizontalAlignment switch
		{
			HorizontalAlignment.Left => 0f,
			HorizontalAlignment.Center => 0.5f,
			HorizontalAlignment.Right => 1f,
			_ => 0.5f,
		};

		float alignY = VerticalAlignment switch
		{
			VerticalAlignment.Top => 0f,
			VerticalAlignment.Center => 0.5f,
			VerticalAlignment.Bottom => 1f,
			_ => 0.5f,
		};

		float offsetX = alignX * (1f / scale.x - 1f);
		float offsetY = alignY * (1f / scale.y - 1f);

		Style.UvOffset = new Vector2( offsetX, offsetY );
	}
}
using Sandbox.UiPro;

namespace Sandbox;

// Hooks up the Button's OnClick event and responds
// by updating the TextNode
public class ExampleButtonController : Component
{
	[Property] public Button MyButton { get; set; }
	[Property] public TextNode MyText { get; set; }
	[Property, ReadOnly] public int ClickCount { get; set; } = 0;

	protected override void OnStart()
	{
		if ( !MyButton.IsValid() ) return;

		MyButton.OnClick = OnButtonClicked;
	}

	private void OnButtonClicked()
	{
		ClickCount++;

		if ( !MyText.IsValid() ) return;

		TextRendering.Scope scope = MyText.TextScope;
		scope.Text = $"Clicked {ClickCount} Times";
		MyText.TextScope = scope;
	}
}
using System;

namespace Sandbox.UiPro;

public enum NodePoint
{
	TopLeft, TopMiddle, TopRight,
	CenterLeft, CenterMiddle, CenterRight,
	BottomLeft, BottomMiddle, BottomRight,
}

public class NodeStyle
{
	[Property] public NodePoint Anchor { get; set; }
	[Property] public NodePoint Pivot { get; set; }
	[Property] public Vector2 Offset { get; set; }
	[Property] public Vector2 Size { get; set; }
	[Property] public Vector4 ChildPadding { get; set; }
	[Property] public bool ClipChildren { get; set; }
	[Property] public bool StretchHorizontal { get; set; }
	[Property] public bool StretchVertical { get; set; }
	
	[Property, Hide] public float CornerRadius { get; set; }
	[Property, Hide] public float BorderWidth { get; set; }
	[Property, Hide] public Color BorderColor { get; set; }
	[Property, Hide] public Texture Texture { get; set; }
	[Property, Hide] public Color Tint { get; set; }
	[Property, Hide] public Vector2 UvScale { get; set; }
	[Property, Hide] public Vector2 UvOffset { get; set; }
}

public class NodeLayout
{
	public Rect Outer { get; private set; }
	public Rect Inner { get; private set; }
	public Rect ClipRect { get; private set; }
	public float ClipRadius { get; private set; }
	public Rect ChildClipRect { get; private set; }
	public float ChildClipRadius { get; private set; }

	public static NodeLayout GetRootLayout( Vector2 size )
	{
		Rect rootRect = new Rect( Vector2.Zero, size );

		NodeLayout layout = new NodeLayout()
		{
			Outer = rootRect,
			Inner = rootRect,
			ClipRect = rootRect,
			ClipRadius = 0,
			ChildClipRect = rootRect,
			ChildClipRadius = 0
		};

		return layout;
	}

	public void Compute( NodeLayout parentLayout, NodeStyle style )
	{
		Vector2 anchor = AnchorFraction( style.Anchor );
		Vector2 pivot = AnchorFraction( style.Pivot );

		float width = style.StretchHorizontal ? parentLayout.Inner.Size.x : style.Size.x;
		float height = style.StretchVertical ? parentLayout.Inner.Size.y : style.Size.y;

		float x = style.StretchHorizontal
			? parentLayout.Inner.Position.x + style.Offset.x
			: parentLayout.Inner.Position.x + anchor.x * parentLayout.Inner.Size.x - pivot.x * width + style.Offset.x;

		float y = style.StretchVertical
			? parentLayout.Inner.Position.y + style.Offset.y
			: parentLayout.Inner.Position.y + anchor.y * parentLayout.Inner.Size.y - pivot.y * height + style.Offset.y;

		Outer = new Rect( new Vector2( x, y ), new Vector2( width, height ) );

		float innerW = Math.Max( 0f, width - style.ChildPadding.x - style.ChildPadding.z );
		float innerH = Math.Max( 0f, height - style.ChildPadding.y - style.ChildPadding.w );
		Inner = new Rect( new Vector2( x + style.ChildPadding.x, y + style.ChildPadding.y ), new Vector2( innerW, innerH ) );

		ClipRect = parentLayout.ChildClipRect;
		ClipRadius = parentLayout.ChildClipRadius;

		if ( style.ClipChildren )
		{
			float bw = Math.Max( 0f, style.BorderWidth );
			float clipW = Math.Max( 0f, Outer.Size.x - bw * 2f );
			float clipH = Math.Max( 0f, Outer.Size.y - bw * 2f );

			ChildClipRect = new Rect( new Vector2( Outer.Position.x + bw, Outer.Position.y + bw ), new Vector2( clipW, clipH ) );
			ChildClipRadius = Math.Max( 0f, style.CornerRadius - bw );
		}
		else
		{
			ChildClipRect = parentLayout.ChildClipRect;
			ChildClipRadius = parentLayout.ChildClipRadius;
		}
	}

	private static Vector2 AnchorFraction( NodePoint point )
	{
		float fx = point switch
		{
			NodePoint.TopLeft or NodePoint.CenterLeft or NodePoint.BottomLeft => 0f,
			NodePoint.TopMiddle or NodePoint.CenterMiddle or NodePoint.BottomMiddle => 0.5f,
			_ => 1f,
		};
		float fy = point switch
		{
			NodePoint.TopLeft or NodePoint.TopMiddle or NodePoint.TopRight => 0f,
			NodePoint.CenterLeft or NodePoint.CenterMiddle or NodePoint.CenterRight => 0.5f,
			_ => 1f,
		};
		return new Vector2( fx, fy );
	}
}
global using Sandbox;
global using Editor;
global using System.Collections.Generic;
global using System.Linq;
global using Dreams.UltimateLightManager;
using Sandbox;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Dreams.UltimateLightManager;

[Library( "UltimateLightManager" )]
[Title( "Ultimate Light Manager" )]
[Description( "Advanced light component with presets, runtime controls, grouping, and an integrated S&box editor workflow." )]
[Category( "Light" )]
[Icon( "tungsten" )]
public class UltimateLightManager : Component, Component.ExecuteInEditor
{
    public enum LightTypeEnum
    {
        Point,
        Spot
    }

    public enum LightPreset
    {
        Custom,
        Candle,
        Torch,
        Neon,
        Alarm,
        BrokenLamp,
        SciFi,
        StreetLight
    }

    public static void SetGroupState( string groupName, bool isEnabled )
    {
        foreach ( var light in GetLightsInGroup( groupName ) )
        {
            light.SetEnabledState( isEnabled );
        }
    }

    public static void SetGroupBrightness( string groupName, float brightness )
    {
        brightness = Math.Max( brightness, 0f );

        foreach ( var light in GetLightsInGroup( groupName ) )
        {
            light.SetBrightnessLevel( brightness );
        }
    }

    public static void SetGroupColor( string groupName, Color color )
    {
        foreach ( var light in GetLightsInGroup( groupName ) )
        {
            light.SetLightColorValue( color );
        }
    }

    public static void ApplyPresetToGroup( string groupName, LightPreset preset )
    {
        foreach ( var light in GetLightsInGroup( groupName ) )
        {
            light.ApplyPreset( preset );
        }
    }

    public static void TriggerGroupFlash( string groupName, float duration = 0.15f, float brightnessMultiplier = 2f )
    {
        foreach ( var light in GetLightsInGroup( groupName ) )
        {
            light.TriggerFlash( duration, brightnessMultiplier );
        }
    }

    public static void TriggerGroupAlarm( string groupName, float duration = 2f )
    {
        foreach ( var light in GetLightsInGroup( groupName ) )
        {
            light.TriggerAlarm( duration );
        }
    }

    public static void SetPowerGridState( string powerGridTag, bool isPowered )
    {
        foreach ( var light in GetLightsInPowerGrid( powerGridTag ) )
        {
            light.SetPowered( isPowered );
        }
    }

    private static IEnumerable<UltimateLightManager> GetLightsInGroup( string groupName )
    {
        return EnumerateAllLights().Where( light => string.Equals( light.LightGroup, groupName, StringComparison.OrdinalIgnoreCase ) );
    }

    private static IEnumerable<UltimateLightManager> GetLightsInPowerGrid( string powerGridTag )
    {
        return EnumerateAllLights().Where( light => string.Equals( light.PowerGridTag, powerGridTag, StringComparison.OrdinalIgnoreCase ) );
    }

    private static IEnumerable<UltimateLightManager> EnumerateAllLights()
    {
        var visitedScenes = new HashSet<Scene>();
        var visitedLights = new HashSet<UltimateLightManager>();

        foreach ( var scene in EnumerateCandidateScenes() )
        {
            if ( scene == null || !visitedScenes.Add( scene ) )
            {
                continue;
            }

            foreach ( var light in scene.GetAllComponents<UltimateLightManager>() )
            {
                if ( light != null && visitedLights.Add( light ) )
                {
                    yield return light;
                }
            }
        }
    }

    private static IEnumerable<Scene> EnumerateCandidateScenes()
    {
        if ( Game.ActiveScene != null )
        {
            yield return Game.ActiveScene;
        }

        foreach ( var scene in Scene.All )
        {
            if ( scene != null )
            {
                yield return scene;
            }
        }
    }

    [Property, Order( -1 ), Group( "Management" )]
    public string LightGroup { get; set; } = "Default";

    [Property, Group( "Management" )]
    public string PowerGridTag { get; set; } = string.Empty;

    [Property, Group( "Management" )]
    public float StartDelay { get; set; } = 0.0f;

    [Property, Group( "Management" )]
    public bool AutoDesync { get; set; } = true;

    [Property, Group( "Management" )]
    public bool ShowDebugGizmos { get; set; } = false;

    [Property, Group( "Management" )]
    public bool ForceNetworkObjectMode { get; set; } = true;

    [Property, Group( "General" ), Sync( SyncFlags.FromHost )]
    public LightTypeEnum TargetLightType { get; set; } = LightTypeEnum.Point;

    [Property, Group( "General" ), Sync( SyncFlags.FromHost )]
    public bool IsEnabled { get; set; } = true;

    [Property, Group( "General" ), Sync( SyncFlags.FromHost )]
    public Color LightColor { get; set; } = Color.White;

    [Property, Group( "General" ), Range( 0, 100 ), Sync( SyncFlags.FromHost | SyncFlags.Interpolate )]
    public float Brightness { get; set; } = 1.0f;

    [Property, Group( "General" ), Range( 0, 10 )]
    public float VolumetricBoost { get; set; } = 1.0f;

    [Property, Group( "General" )]
    public bool CastShadows { get; set; } = true;

    [Property, Group( "Presets" ), Sync( SyncFlags.FromHost )]
    public LightPreset SelectedPreset { get; set; } = LightPreset.Custom;

    [Property, Group( "Presets" ), Sync( SyncFlags.FromHost )]
    public bool AutoApplyPreset { get; set; } = true;

    [Property, Group( "Transitions" )]
    public bool EnableFade { get; set; } = false;

    [Property, Group( "Transitions" )]
    public float FadeInDuration { get; set; } = 0.2f;

    [Property, Group( "Transitions" )]
    public float FadeOutDuration { get; set; } = 0.2f;

    [Property, Group( "Audio" )]
    public SoundEvent AmbientSound { get; set; }

    [Property, Group( "Audio" )]
    public SoundEvent ToggleOnSound { get; set; }

    [Property, Group( "Audio" )]
    public SoundEvent ToggleOffSound { get; set; }

    [Property, Group( "Audio" )]
    public bool ModulateVolumeWithLight { get; set; } = true;

    [Property, Group( "Audio" )]
    public bool ModulatePitchWithLight { get; set; } = false;

    [Property, Group( "Audio" ), Range( 0, 5 )]
    public float BaseVolume { get; set; } = 1.0f;

    [Property, Group( "Audio" ), Range( 0.5f, 2f )]
    public float MinPitch { get; set; } = 0.9f;

    [Property, Group( "Audio" ), Range( 0.5f, 2f )]
    public float MaxPitch { get; set; } = 1.1f;

    [Property, Group( "Optimization" )]
    public float MaxDistance { get; set; } = 2500.0f;

    [Property, Group( "Optimization" )]
    public float ShadowMaxDistance { get; set; } = 800.0f;

    [Property, Group( "Optimization" )]
    public bool EnableCulling { get; set; } = true;

    [Property, Group( "Optimization" )]
    public bool EnableAdaptiveUpdates { get; set; } = false;

    [Property, Group( "Optimization" ), Range( 1, 120 )]
    public float NearUpdateRate { get; set; } = 60.0f;

    [Property, Group( "Optimization" ), Range( 1, 120 )]
    public float FarUpdateRate { get; set; } = 12.0f;

    [Property, Group( "Gameplay" )]
    public float DefaultAlarmDuration { get; set; } = 2.0f;

    [Property, Group( "Gameplay" ), Sync( SyncFlags.FromHost )]
    public Color AlarmColor { get; set; } = new Color( 1.0f, 0.15f, 0.1f );

    [Property, Group( "Gameplay" )]
    public float AlarmStrobeSpeed { get; set; } = 8.0f;

    [Property, Group( "Gameplay" )]
    public float AlarmBrightnessMultiplier { get; set; } = 1.5f;

    [Property, FeatureEnabled( "Fire & Candle" )]
    public bool EnableFire { get; set; } = false;

    [Property, Feature( "Fire & Candle" )]
    public float FireSpeed { get; set; } = 12.0f;

    [Property, Feature( "Fire & Candle" ), Range( 0, 1 )]
    public float FireIntensity { get; set; } = 0.3f;

    [Property, Feature( "Fire & Candle" ), Range( 0, 2 )]
    public float FireChaos { get; set; } = 1.0f;

    [Property, FeatureEnabled( "Horror Mode" )]
    public bool EnableHorror { get; set; } = false;

    [Property, Feature( "Horror Mode" )]
    public float MinFlickerDelay { get; set; } = 0.05f;

    [Property, Feature( "Horror Mode" )]
    public float MaxFlickerDelay { get; set; } = 0.4f;

    [Property, Feature( "Horror Mode" ), Range( 0, 1 )]
    public float DamageSeverity { get; set; } = 0.8f;

    [Property, Feature( "Horror Mode" )]
    public SoundEvent SparkSound { get; set; }

    [Property, FeatureEnabled( "Disco Mode" )]
    public bool EnableDisco { get; set; } = false;

    [Property, Feature( "Disco Mode" )]
    public float DiscoSpeed { get; set; } = 20.0f;

    [Property, Feature( "Disco Mode" ), Range( 0, 1 )]
    public float DiscoSaturation { get; set; } = 1.0f;

    [Property, Feature( "Disco Mode" ), Range( 0, 1 )]
    public float DiscoValue { get; set; } = 1.0f;

    [Property, FeatureEnabled( "Color Transition" )]
    public bool EnableColorTransition { get; set; } = false;

    [Property, Feature( "Color Transition" ), Sync( SyncFlags.FromHost )]
    public Color SecondaryColor { get; set; } = new Color( 0.2f, 0.85f, 1.0f );

    [Property, Feature( "Color Transition" )]
    public float ColorTransitionSpeed { get; set; } = 1.0f;

    [Property, FeatureEnabled( "Proximity Sensor" )]
    public bool EnableSensor { get; set; } = false;

    [Property, Feature( "Proximity Sensor" )]
    public float SensorRange { get; set; } = 300.0f;

    [Property, Feature( "Proximity Sensor" ), Range( 0, 1 )]
    public float SensorMinBrightness { get; set; } = 0.0f;

    [Property, Feature( "Proximity Sensor" ), Range( 0, 1 )]
    public float SensorMaxBrightness { get; set; } = 1.0f;

    [Property, Feature( "Proximity Sensor" ), Range( 1, 20 )]
    public float SensorSmoothness { get; set; } = 5.0f;

    [Property, Feature( "Proximity Sensor" )]
    public bool InvertSensor { get; set; } = false;

    [Property, FeatureEnabled( "Motion Sway" )]
    public bool EnableSway { get; set; } = false;

    [Property, Feature( "Motion Sway" )]
    public float SwaySpeedPitch { get; set; } = 1.0f;

    [Property, Feature( "Motion Sway" )]
    public float SwayAmountPitch { get; set; } = 5.0f;

    [Property, Feature( "Motion Sway" )]
    public float SwaySpeedRoll { get; set; } = 0.7f;

    [Property, Feature( "Motion Sway" )]
    public float SwayAmountRoll { get; set; } = 3.0f;

    [Property, FeatureEnabled( "Flicker Pattern" )]
    public bool EnablePattern { get; set; } = false;

    [Property, Feature( "Flicker Pattern" )]
    public string Pattern { get; set; } = "mmnmmommommnonmmonqnmmo";

    [Property, Feature( "Flicker Pattern" )]
    public float PatternSpeed { get; set; } = 10.0f;

    [Property, FeatureEnabled( "Pulse" )]
    public bool EnablePulse { get; set; } = false;

    [Property, Feature( "Pulse" )]
    public float PulseSpeed { get; set; } = 1.0f;

    [Property, Feature( "Pulse" ), Range( 0, 1 )]
    public float PulseMin { get; set; } = 0.2f;

    [Property, FeatureEnabled( "Strobe" )]
    public bool EnableStrobe { get; set; } = false;

    [Property, Feature( "Strobe" )]
    public float StrobeSpeed { get; set; } = 10.0f;

    [Property, Feature( "Strobe" ), Range( 0.1f, 0.9f )]
    public float StrobeDutyCycle { get; set; } = 0.5f;

    [Property, FeatureEnabled( "Kelvin" )]
    public bool EnableKelvin { get; set; } = false;

    [Property, Feature( "Kelvin" ), Range( 1000, 12000 )]
    public int KelvinTemperature { get; set; } = 4500;

    [Property, FeatureEnabled( "Power Surge" )]
    public bool EnablePowerSurge { get; set; } = false;

    [Property, Feature( "Power Surge" )]
    public float SurgeMinInterval { get; set; } = 4.0f;

    [Property, Feature( "Power Surge" )]
    public float SurgeMaxInterval { get; set; } = 10.0f;

    [Property, Feature( "Power Surge" )]
    public float SurgeDuration { get; set; } = 0.15f;

    [Property, Feature( "Power Surge" )]
    public float SurgeBrightnessMultiplier { get; set; } = 1.8f;

    public bool Powered => PoweredState;
    public float ExternalBrightnessMultiplier => ExternalBrightnessMultiplierState;
    public bool HasColorOverride => HasExternalColorOverrideState;
    public bool AlarmActive => AlarmEndTimeState > RealTime.Now;

    private PointLight _pointLight;
    private SpotLight _spotLight;
    private Light ActiveLight => TargetLightType == LightTypeEnum.Point ? (Light)_pointLight : _spotLight;

    private int _lastKelvin = -1;
    private Color _cachedKelvinColor = Color.White;
    private Rotation _baseRotation;
    private bool _isInitialized;
    private bool _hasAppliedPreset;
    private LightPreset _lastAppliedPreset = LightPreset.Custom;
    private LightPreset _lastObservedPreset = LightPreset.Custom;
    private bool _lastObservedAutoApplyPreset = true;
    private LightTypeEnum _lastSyncedLightType = LightTypeEnum.Point;
    private float _brokenMultiplier = 1.0f;
    private float _nextFlicker;
    private float _sensorWeightTarget = 1.0f;
    private float _sensorWeightCurrent = 1.0f;
    private float _randomTimeOffset;
    private float _creationTime;
    private float _lastUpdateTimestamp;
    private float _enabledBlend = 1.0f;
    private float _nextAdaptiveUpdateTime;
    private float _nextViewerCameraRefreshTime;
    private float _nextSurgeTime;
    private float _surgeEndTime;
    private bool _hasOutputState;
    private bool _lastOutputEnabled;
    private CameraComponent _cachedViewerCamera;
    private SoundHandle _ambientSoundHandle;

    [Sync( SyncFlags.FromHost )]
    private bool PoweredState { get; set; } = true;

    [Sync( SyncFlags.FromHost | SyncFlags.Interpolate )]
    private float ExternalBrightnessMultiplierState { get; set; } = 1.0f;

    [Sync( SyncFlags.FromHost )]
    private bool HasExternalColorOverrideState { get; set; }

    [Sync( SyncFlags.FromHost )]
    private Color ExternalColorOverrideState { get; set; } = Color.White;

    [Sync( SyncFlags.FromHost )]
    private float FlashEndTimeState { get; set; }

    [Sync( SyncFlags.FromHost )]
    private float FlashBrightnessMultiplierState { get; set; } = 1.0f;

    [Sync( SyncFlags.FromHost )]
    private float AlarmEndTimeState { get; set; }

    protected override void OnAwake()
    {
        EnsureNetworkMode();
    }

    protected override void OnStart()
    {
        EnsureNetworkMode();

        _baseRotation = LocalRotation;
        _creationTime = RealTime.Now;
        _lastUpdateTimestamp = _creationTime;
        _enabledBlend = IsEnabled ? 1.0f : 0.0f;

        if ( AutoDesync )
        {
            _randomTimeOffset = Game.Random.Float( 0f, 100f );
        }

        SyncComponentsIfNeeded( force: true );

        if ( AutoApplyPreset )
        {
            ApplyPresetInternal( SelectedPreset );
        }

        ScheduleNextSurge( _creationTime );

        _lastObservedPreset = SelectedPreset;
        _lastObservedAutoApplyPreset = AutoApplyPreset;
        _isInitialized = true;
    }

    protected override void OnUpdate()
    {
        if ( !_isInitialized )
        {
            return;
        }

        SyncComponentsIfNeeded();
        SyncPresetSelectionIfNeeded();

        var light = ActiveLight;
        if ( light == null )
        {
            return;
        }

        bool isPlaying = Game.IsPlaying;
        float absoluteTime = RealTime.Now;
        float effectTime = (isPlaying ? Time.Now : absoluteTime) + _randomTimeOffset;
        float deltaTime = GetFrameDelta( absoluteTime );

        if ( isPlaying && StartDelay > 0f && (absoluteTime - _creationTime) < StartDelay )
        {
            DisableOutput( light );
            return;
        }

        var viewerCam = GetViewerCamera( absoluteTime );
        float distSq = viewerCam != null ? WorldPosition.DistanceSquared( viewerCam.WorldPosition ) : 0f;

        if ( ShouldSkipAdaptiveUpdate( isPlaying, viewerCam, distSq, absoluteTime ) )
        {
            UpdateAmbientSoundPosition();
            return;
        }

        UpdateSensorWeight( viewerCam, distSq, deltaTime );
        UpdateEnabledBlend( deltaTime );
        UpdateSway( effectTime );

        if ( isPlaying && EnableCulling && viewerCam != null && distSq > MaxDistance * MaxDistance )
        {
            DisableOutput( light );
            return;
        }

        float fx = 1.0f;

        fx *= EvaluatePulseAndStrobe( effectTime );
        fx *= EvaluatePattern( effectTime );
        fx *= EvaluateFire( effectTime );
        fx *= EvaluateHorror( effectTime, isPlaying );
        fx *= EvaluatePowerSurge( absoluteTime );
        fx *= EvaluateAlarm( effectTime, absoluteTime );

        if ( absoluteTime < FlashEndTimeState )
        {
            fx *= FlashBrightnessMultiplierState;
        }

        float finalBrightness = Brightness * fx * _sensorWeightCurrent * _enabledBlend * ExternalBrightnessMultiplierState;
        finalBrightness = Math.Max( finalBrightness, 0f );

        bool shouldBeEnabled = finalBrightness > 0.001f;
        light.Enabled = shouldBeEnabled;

        Color resolvedColor = ResolveLightColor( effectTime, absoluteTime );
        light.LightColor = resolvedColor * finalBrightness;
        light.Shadows = CastShadows && ( !isPlaying || distSq < ShadowMaxDistance * ShadowMaxDistance );
        light.FogStrength = VolumetricBoost;

        UpdateOutputState( shouldBeEnabled, true );
        ManageAudio( shouldBeEnabled, finalBrightness / Math.Max( Brightness, 0.01f ) );
    }

    public void TurnOn()
    {
        SetEnabledState( true );
    }

    [Button]
    public void ApplySelectedPreset()
    {
        ApplyPreset( SelectedPreset );
    }

    public void TurnOff()
    {
        SetEnabledState( false );
    }

    public void Toggle()
    {
        if ( ShouldIgnoreNetworkMutation() )
        {
            return;
        }

        IsEnabled = !IsEnabled;
    }

    public void SetPowered( bool powered )
    {
        if ( ShouldIgnoreNetworkMutation() )
        {
            return;
        }

        PoweredState = powered;
    }

    public void SetExternalBrightness( float multiplier )
    {
        if ( ShouldIgnoreNetworkMutation() )
        {
            return;
        }

        ExternalBrightnessMultiplierState = Math.Max( multiplier, 0f );
    }

    public void ResetExternalBrightness()
    {
        if ( ShouldIgnoreNetworkMutation() )
        {
            return;
        }

        ExternalBrightnessMultiplierState = 1.0f;
    }

    public void SetColorOverride( Color color )
    {
        if ( ShouldIgnoreNetworkMutation() )
        {
            return;
        }

        HasExternalColorOverrideState = true;
        ExternalColorOverrideState = color;
    }

    public void ClearColorOverride()
    {
        if ( ShouldIgnoreNetworkMutation() )
        {
            return;
        }

        HasExternalColorOverrideState = false;
        ExternalColorOverrideState = Color.White;
    }

    public void TriggerFlash( float duration = 0.15f, float brightnessMultiplier = 2f )
    {
        if ( ShouldIgnoreNetworkMutation() )
        {
            return;
        }

        FlashEndTimeState = RealTime.Now + Math.Max( duration, 0.01f );
        FlashBrightnessMultiplierState = Math.Max( brightnessMultiplier, 1.0f );
    }

    public void TriggerAlarm( float duration = -1f )
    {
        if ( ShouldIgnoreNetworkMutation() )
        {
            return;
        }

        if ( duration <= 0f )
        {
            duration = DefaultAlarmDuration;
        }

        AlarmEndTimeState = Math.Max( AlarmEndTimeState, RealTime.Now + duration );
    }

    public void ClearAlarm()
    {
        if ( ShouldIgnoreNetworkMutation() )
        {
            return;
        }

        AlarmEndTimeState = 0f;
    }

    [Button]
    public void PreviewFlash()
    {
        TriggerFlash();
    }

    [Button]
    public void PreviewAlarm()
    {
        TriggerAlarm();
    }

    [Button]
    public void ResetRuntimeOverrides()
    {
        if ( ShouldIgnoreNetworkMutation() )
        {
            return;
        }

        ClearAlarm();
        ClearColorOverride();
        ResetExternalBrightness();
        SetPowered( true );
    }

    public void ApplyPreset( LightPreset preset )
    {
        if ( ShouldIgnoreNetworkMutation() )
        {
            return;
        }

        ApplyPresetInternal( preset );
    }

    public void SetEnabledState( bool isEnabled )
    {
        if ( ShouldIgnoreNetworkMutation() )
        {
            return;
        }

        IsEnabled = isEnabled;
    }

    public void SetBrightnessLevel( float brightness )
    {
        if ( ShouldIgnoreNetworkMutation() )
        {
            return;
        }

        Brightness = Math.Max( brightness, 0f );
    }

    public void SetLightColorValue( Color color )
    {
        if ( ShouldIgnoreNetworkMutation() )
        {
            return;
        }

        LightColor = color;
    }

    private void ApplyPresetInternal( LightPreset preset )
    {
        SelectedPreset = preset;
        ResetPresetControlledFeatures();

        switch ( preset )
        {
            case LightPreset.Candle:
                Brightness = 0.75f;
                LightColor = new Color( 1.0f, 0.76f, 0.5f );
                SecondaryColor = new Color( 1.0f, 0.66f, 0.35f );
                EnableKelvin = true;
                KelvinTemperature = 1800;
                EnableFire = true;
                FireSpeed = 10.0f;
                FireIntensity = 0.18f;
                FireChaos = 0.6f;
                VolumetricBoost = 0.6f;
                break;

            case LightPreset.Torch:
                Brightness = 1.35f;
                LightColor = new Color( 1.0f, 0.72f, 0.38f );
                SecondaryColor = new Color( 1.0f, 0.45f, 0.2f );
                EnableKelvin = true;
                KelvinTemperature = 2200;
                EnableFire = true;
                FireSpeed = 13.0f;
                FireIntensity = 0.28f;
                FireChaos = 1.0f;
                VolumetricBoost = 1.4f;
                break;

            case LightPreset.Neon:
                Brightness = 1.15f;
                LightColor = new Color( 0.2f, 0.95f, 1.0f );
                SecondaryColor = new Color( 1.0f, 0.2f, 0.85f );
                EnableColorTransition = true;
                ColorTransitionSpeed = 0.65f;
                EnablePulse = true;
                PulseSpeed = 1.2f;
                PulseMin = 0.75f;
                CastShadows = false;
                VolumetricBoost = 0.25f;
                break;

            case LightPreset.Alarm:
                Brightness = 2.0f;
                LightColor = new Color( 1.0f, 0.18f, 0.12f );
                AlarmColor = LightColor;
                EnableStrobe = true;
                StrobeSpeed = 7.0f;
                StrobeDutyCycle = 0.45f;
                CastShadows = false;
                VolumetricBoost = 1.1f;
                break;

            case LightPreset.BrokenLamp:
                Brightness = 1.0f;
                LightColor = new Color( 1.0f, 0.93f, 0.82f );
                EnableHorror = true;
                MinFlickerDelay = 0.04f;
                MaxFlickerDelay = 0.25f;
                DamageSeverity = 0.85f;
                EnableKelvin = true;
                KelvinTemperature = 3400;
                break;

            case LightPreset.SciFi:
                Brightness = 1.6f;
                LightColor = new Color( 0.35f, 0.78f, 1.0f );
                SecondaryColor = new Color( 0.1f, 1.0f, 0.8f );
                EnableColorTransition = true;
                ColorTransitionSpeed = 1.15f;
                EnablePulse = true;
                PulseSpeed = 0.85f;
                PulseMin = 0.55f;
                VolumetricBoost = 2.0f;
                break;

            case LightPreset.StreetLight:
                Brightness = 1.4f;
                LightColor = new Color( 1.0f, 0.84f, 0.68f );
                EnableKelvin = true;
                KelvinTemperature = 3500;
                MaxDistance = 4500.0f;
                ShadowMaxDistance = 1200.0f;
                VolumetricBoost = 0.55f;
                break;

            case LightPreset.Custom:
            default:
                break;
        }

        _lastAppliedPreset = preset;
        _hasAppliedPreset = true;
    }

    private void ResetPresetControlledFeatures()
    {
        EnableFire = false;
        EnableHorror = false;
        EnableDisco = false;
        EnableColorTransition = false;
        EnablePulse = false;
        EnableStrobe = false;
        EnableKelvin = false;
    }

    private void SyncPresetSelectionIfNeeded()
    {
        bool autoApplyChanged = AutoApplyPreset != _lastObservedAutoApplyPreset;
        bool presetChanged = SelectedPreset != _lastObservedPreset;

        _lastObservedAutoApplyPreset = AutoApplyPreset;
        _lastObservedPreset = SelectedPreset;

        if ( !AutoApplyPreset )
        {
            return;
        }

        if ( autoApplyChanged || presetChanged || !_hasAppliedPreset || SelectedPreset != _lastAppliedPreset )
        {
            ApplyPresetInternal( SelectedPreset );
        }
    }

    private void SyncComponentsIfNeeded( bool force = false )
    {
        bool missingActiveLight = TargetLightType == LightTypeEnum.Point ? _pointLight == null : _spotLight == null;
        if ( !force && !missingActiveLight && TargetLightType == _lastSyncedLightType )
        {
            return;
        }

        Component createdComponent = null;

        if ( TargetLightType == LightTypeEnum.Point )
        {
            if ( _pointLight == null )
            {
                _pointLight = Components.GetOrCreate<PointLight>();
                createdComponent = _pointLight;
            }

            if ( _spotLight != null && _spotLight.Enabled )
            {
                _spotLight.Enabled = false;
            }
        }
        else
        {
            if ( _spotLight == null )
            {
                _spotLight = Components.GetOrCreate<SpotLight>();
                createdComponent = _spotLight;
            }

            if ( _pointLight != null && _pointLight.Enabled )
            {
                _pointLight.Enabled = false;
            }
        }

        _lastSyncedLightType = TargetLightType;

        if ( createdComponent != null && Game.IsPlaying && GameObject.NetworkMode == NetworkMode.Object )
        {
            GameObject.Network.Refresh( createdComponent );
        }
    }

    private CameraComponent GetViewerCamera( float absoluteTime )
    {
        var sceneCamera = Scene.Camera;
        if ( sceneCamera != null )
        {
            _cachedViewerCamera = sceneCamera;
            _nextViewerCameraRefreshTime = absoluteTime + 0.25f;
            return sceneCamera;
        }

        if ( _cachedViewerCamera != null && absoluteTime < _nextViewerCameraRefreshTime )
        {
            return _cachedViewerCamera;
        }

        _nextViewerCameraRefreshTime = absoluteTime + 0.25f;
        _cachedViewerCamera = Scene.GetAllComponents<CameraComponent>().FirstOrDefault( camera => camera != null && camera.Enabled );
        return _cachedViewerCamera;
    }

    private void EnsureNetworkMode()
    {
        if ( !ForceNetworkObjectMode || !Game.IsPlaying || GameObject.NetworkMode == NetworkMode.Object )
        {
            return;
        }

        GameObject.NetworkMode = NetworkMode.Object;
    }

    private bool ShouldIgnoreNetworkMutation()
    {
        return Game.IsPlaying && IsProxy;
    }

    private float GetFrameDelta( float absoluteTime )
    {
        float delta = Math.Clamp( absoluteTime - _lastUpdateTimestamp, 0.0001f, 0.25f );
        _lastUpdateTimestamp = absoluteTime;
        return delta;
    }

    private bool ShouldSkipAdaptiveUpdate( bool isPlaying, CameraComponent viewerCam, float distSq, float absoluteTime )
    {
        if ( !EnableAdaptiveUpdates || !isPlaying || viewerCam == null )
        {
            return false;
        }

        if ( absoluteTime < _nextAdaptiveUpdateTime )
        {
            return true;
        }

        float maxDistanceSq = Math.Max( MaxDistance * MaxDistance, 1f );
        float distRatio = Math.Clamp( distSq / maxDistanceSq, 0f, 1f );
        float nearInterval = 1f / Math.Max( NearUpdateRate, 1f );
        float farInterval = 1f / Math.Max( FarUpdateRate, 1f );
        _nextAdaptiveUpdateTime = absoluteTime + MathX.Lerp( nearInterval, farInterval, distRatio );
        return false;
    }

    private void UpdateSensorWeight( CameraComponent viewerCam, float distSq, float deltaTime )
    {
        if ( EnableSensor && viewerCam != null && SensorRange > 0.01f )
        {
            float distRatio = Math.Clamp( 1.0f - (MathF.Sqrt( distSq ) / SensorRange), 0f, 1f );
            float rawWeight = InvertSensor ? 1.0f - distRatio : distRatio;
            _sensorWeightTarget = MathX.Lerp( SensorMinBrightness, SensorMaxBrightness, rawWeight );
        }
        else
        {
            _sensorWeightTarget = 1.0f;
        }

        _sensorWeightCurrent = MathX.Lerp( _sensorWeightCurrent, _sensorWeightTarget, Math.Clamp( deltaTime * SensorSmoothness, 0f, 1f ) );
    }

    private void UpdateEnabledBlend( float deltaTime )
    {
        float target = IsEnabled && PoweredState ? 1.0f : 0.0f;

        if ( !EnableFade )
        {
            _enabledBlend = target;
            return;
        }

        float duration = target > _enabledBlend ? Math.Max( FadeInDuration, 0.0001f ) : Math.Max( FadeOutDuration, 0.0001f );
        float lerp = Math.Clamp( deltaTime / duration, 0f, 1f );
        _enabledBlend = MathX.Lerp( _enabledBlend, target, lerp );

        if ( Math.Abs( _enabledBlend - target ) < 0.001f )
        {
            _enabledBlend = target;
        }
    }

    private void UpdateSway( float effectTime )
    {
        if ( EnableSway )
        {
            float pitch = MathF.Sin( effectTime * SwaySpeedPitch ) * SwayAmountPitch;
            float roll = MathF.Cos( effectTime * SwaySpeedRoll ) * SwayAmountRoll;
            LocalRotation = _baseRotation * Rotation.From( pitch, 0f, roll );
            return;
        }

        LocalRotation = _baseRotation;
    }

    private float EvaluatePulseAndStrobe( float effectTime )
    {
        if ( EnableStrobe )
        {
            float cycle = (effectTime * StrobeSpeed) % 1.0f;
            return cycle < StrobeDutyCycle ? 1.0f : 0.0f;
        }

        if ( EnablePulse )
        {
            float sine = (MathF.Sin( effectTime * PulseSpeed * 2.0f ) + 1.0f) * 0.5f;
            return MathX.Lerp( PulseMin, 1.0f, sine );
        }

        return 1.0f;
    }

    private float EvaluatePattern( float effectTime )
    {
        if ( !EnablePattern || string.IsNullOrWhiteSpace( Pattern ) )
        {
            return 1.0f;
        }

        int index = (int)(effectTime * PatternSpeed) % Pattern.Length;
        float value = Math.Max( 0, (char.ToLower( Pattern[index] ) - 'a') / 12.0f );
        return value;
    }

    private float EvaluateFire( float effectTime )
    {
        if ( !EnableFire )
        {
            return 1.0f;
        }

        float noise = MathF.Sin( effectTime * FireSpeed ) + MathF.Sin( effectTime * FireSpeed * 0.5f );

        if ( FireChaos > 0f )
        {
            noise += MathF.Sin( effectTime * FireSpeed * 1.5f ) * FireChaos;
        }

        return 1.0f - (noise * 0.15f * FireIntensity);
    }

    private float EvaluateHorror( float effectTime, bool isPlaying )
    {
        if ( !EnableHorror )
        {
            return 1.0f;
        }

        if ( effectTime > _nextFlicker )
        {
            bool isDamaged = Game.Random.Float( 0f, 1f ) < DamageSeverity;
            _brokenMultiplier = isDamaged ? Game.Random.Float( 0.0f, 0.4f ) : 1.0f;
            _nextFlicker = effectTime + Game.Random.Float( MinFlickerDelay, MaxFlickerDelay );

            if ( isPlaying && isDamaged && SparkSound != null && _brokenMultiplier < 0.2f )
            {
                Sound.Play( SparkSound, WorldPosition );
            }
        }

        return _brokenMultiplier;
    }

    private float EvaluatePowerSurge( float absoluteTime )
    {
        if ( !EnablePowerSurge )
        {
            return 1.0f;
        }

        if ( _nextSurgeTime <= 0f )
        {
            ScheduleNextSurge( absoluteTime );
        }

        if ( absoluteTime >= _nextSurgeTime )
        {
            _surgeEndTime = absoluteTime + Math.Max( SurgeDuration, 0.01f );
            ScheduleNextSurge( _surgeEndTime );
        }

        return absoluteTime < _surgeEndTime ? Math.Max( SurgeBrightnessMultiplier, 1.0f ) : 1.0f;
    }

    private float EvaluateAlarm( float effectTime, float absoluteTime )
    {
        if ( absoluteTime >= AlarmEndTimeState )
        {
            return 1.0f;
        }

        float cycle = (effectTime * AlarmStrobeSpeed) % 1.0f;
        float gate = cycle < 0.5f ? 1.0f : 0.15f;
        return gate * Math.Max( AlarmBrightnessMultiplier, 0f );
    }

    private void ScheduleNextSurge( float absoluteTime )
    {
        float minInterval = Math.Min( SurgeMinInterval, SurgeMaxInterval );
        float maxInterval = Math.Max( SurgeMinInterval, SurgeMaxInterval );
        _nextSurgeTime = absoluteTime + Game.Random.Float( Math.Max( minInterval, 0.01f ), Math.Max( maxInterval, 0.01f ) );
    }

    private Color ResolveLightColor( float effectTime, float absoluteTime )
    {
        Color color = LightColor;

        if ( EnableKelvin )
        {
            if ( KelvinTemperature != _lastKelvin )
            {
                _cachedKelvinColor = KelvinToColor( KelvinTemperature );
                _lastKelvin = KelvinTemperature;
            }

            color = _cachedKelvinColor;
        }

        if ( EnableColorTransition )
        {
            float lerp = (MathF.Sin( effectTime * ColorTransitionSpeed ) + 1.0f) * 0.5f;
            color = Color.Lerp( color, SecondaryColor, lerp, true );
        }

        if ( EnableDisco )
        {
            color = new ColorHsv( (effectTime * DiscoSpeed) % 360f, DiscoSaturation, DiscoValue ).ToColor();
        }

        if ( absoluteTime < AlarmEndTimeState )
        {
            color = Color.Lerp( color, AlarmColor, 0.85f, true );
        }

        if ( HasExternalColorOverrideState )
        {
            color = ExternalColorOverrideState;
        }

        return color;
    }

    private void UpdateOutputState( bool shouldBeEnabled, bool playOneShot )
    {
        if ( !_hasOutputState )
        {
            _hasOutputState = true;
            _lastOutputEnabled = shouldBeEnabled;
            return;
        }

        if ( _lastOutputEnabled == shouldBeEnabled )
        {
            return;
        }

        if ( playOneShot && Game.IsPlaying )
        {
            if ( shouldBeEnabled && ToggleOnSound != null )
            {
                Sound.Play( ToggleOnSound, WorldPosition );
            }
            else if ( !shouldBeEnabled && ToggleOffSound != null )
            {
                Sound.Play( ToggleOffSound, WorldPosition );
            }
        }

        _lastOutputEnabled = shouldBeEnabled;
    }

    private void DisableOutput( Light light )
    {
        light.Enabled = false;
        UpdateOutputState( false, false );
        ManageAudio( false, 0f );
    }

    private void UpdateAmbientSoundPosition()
    {
        if ( _ambientSoundHandle != null && !_ambientSoundHandle.IsStopped )
        {
            _ambientSoundHandle.Position = WorldPosition;
        }
    }

    private void ManageAudio( bool isLightEnabled, float intensityRatio )
    {
        if ( !Game.IsPlaying || AmbientSound == null )
        {
            return;
        }

        if ( isLightEnabled )
        {
            if ( _ambientSoundHandle == null || _ambientSoundHandle.IsStopped )
            {
                _ambientSoundHandle = Sound.Play( AmbientSound, WorldPosition );
            }

            if ( _ambientSoundHandle != null )
            {
                _ambientSoundHandle.Position = WorldPosition;
                _ambientSoundHandle.Volume = BaseVolume * (ModulateVolumeWithLight ? intensityRatio : 1.0f);
                _ambientSoundHandle.Pitch = ModulatePitchWithLight ? MathX.Lerp( MinPitch, MaxPitch, intensityRatio ) : 1.0f;
            }
        }
        else if ( _ambientSoundHandle != null )
        {
            _ambientSoundHandle.Stop();
            _ambientSoundHandle = null;
        }
    }

    private Color KelvinToColor( int kelvin )
    {
        float temperature = kelvin / 100.0f;
        float red;
        float green;
        float blue;

        if ( temperature <= 66f )
        {
            red = 255f;
            green = Math.Clamp( 99.47f * MathF.Log( temperature ) - 161.11f, 0f, 255f );
        }
        else
        {
            red = Math.Clamp( 329.698f * MathF.Pow( temperature - 60f, -0.133f ), 0f, 255f );
            green = Math.Clamp( 288.12f * MathF.Pow( temperature - 60f, -0.075f ), 0f, 255f );
        }

        if ( temperature >= 66f )
        {
            blue = 255f;
        }
        else if ( temperature <= 19f )
        {
            blue = 0f;
        }
        else
        {
            blue = Math.Clamp( 138.51f * MathF.Log( temperature - 10f ) - 305.04f, 0f, 255f );
        }

        return new Color( red / 255f, green / 255f, blue / 255f );
    }

    protected override void DrawGizmos()
    {
        if ( !ShowDebugGizmos )
        {
            return;
        }

        Gizmo.Draw.Text( $"Group: {LightGroup}", new Transform( Vector3.Up * 20f ), size: 12 );

        if ( !string.IsNullOrWhiteSpace( PowerGridTag ) )
        {
            Gizmo.Draw.Text( $"Grid: {PowerGridTag}", new Transform( Vector3.Up * 34f ), size: 12 );
        }

        if ( EnableSensor )
        {
            Gizmo.Draw.Color = Color.Cyan.WithAlpha( 0.2f );
            Gizmo.Draw.SolidSphere( Vector3.Zero, SensorRange );
            Gizmo.Draw.Color = Color.Cyan;
            Gizmo.Draw.LineSphere( Vector3.Zero, SensorRange );
        }

        if ( EnableCulling )
        {
            Gizmo.Draw.Color = Color.Red.WithAlpha( 0.05f );
            Gizmo.Draw.LineSphere( Vector3.Zero, MaxDistance );
            Gizmo.Draw.Text( $"Cull: {MaxDistance}", new Transform( Vector3.Up * (MaxDistance * 0.9f) ), size: 14 );
        }
    }

    protected override void OnDestroy()
    {
        if ( _ambientSoundHandle != null )
        {
            _ambientSoundHandle.Stop();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Editor;
using Sandbox;

namespace Sandbox.AssetBrowserAddon;

/// <summary>
/// Dialog that captures the settings for a new custom Asset Browser location.
/// </summary>
public sealed class LocationEditor : Dialog
{
    private readonly Action<CustomLocationDefinition> _onConfirm;
    private readonly CustomLocationDefinition _initialDefinition;
    private readonly LineEdit _nameInput;
    private readonly LineEdit _iconInput;
    private readonly LineEdit _includeInput;
    private readonly LineEdit _excludeInput;
    private readonly AssetTypeSelector _assetTypeSelector;
    private readonly ToggleSwitch _projectOnlyToggle;

    public LocationEditor(Action<CustomLocationDefinition> onConfirm, CustomLocationDefinition initialDefinition = null)
    {
        _onConfirm = onConfirm;
        _initialDefinition = initialDefinition;

        Window.Title = initialDefinition is null ? "Add Bookmark" : "Edit Bookmark";
        Window.Size = new Vector2(500, 750);

        Layout = Layout.Column();
        Layout.Margin = 16f;
        Layout.Spacing = 12f;

        _nameInput = AddTextRow("Title", "My Bookmark");
        _iconInput = AddIconRow("Icon", "bookmark");

        Layout.Add( new Label( this ) { Text = "Asset Types" } );
        _assetTypeSelector = Layout.Add( new AssetTypeSelector( this, StyleInput ) );

        _projectOnlyToggle = Layout.Add( new ToggleSwitch( "Only include assets from this project", this ) );
        _projectOnlyToggle.MinimumHeight = Theme.RowHeight;
        _projectOnlyToggle.Value = true;

        _includeInput = AddTextArea("Include Folders", "Separate folders with ;");
        _excludeInput = AddTextArea("Exclude Folders", "Separate folders with ;");
        if ( _initialDefinition is not null )
        {
            _nameInput.Text = _initialDefinition.Name;
            _iconInput.Text = _initialDefinition.Icon;
            _assetTypeSelector.SetSelected( _initialDefinition.AssetTypes );
            _includeInput.Text = string.Join( ';', _initialDefinition.IncludeFolders ?? new List<string>() );
            _excludeInput.Text = string.Join( ';', _initialDefinition.ExcludeFolders ?? new List<string>() );
            _projectOnlyToggle.Value = _initialDefinition.ProjectAssetsOnly;

        }

        var buttonRow = Layout.AddRow();
        buttonRow.Spacing = 8f;
        buttonRow.AddStretchCell();
        buttonRow.Add( new Button( "Cancel", this ) { Clicked = Close } );
        var buttonLabel = _initialDefinition is null ? "Add Bookmark" : "Save Bookmark";
        var buttonIcon = _initialDefinition is null ? "add" : "save";
        buttonRow.Add( new Button.Primary( buttonLabel, buttonIcon, this ) { Clicked = Submit } );
    }

    private LineEdit AddTextRow(string label, string placeholder)
    {
        var row = Layout.AddRow();
        row.Spacing = 8f;
        row.Add( new Label( this ) { Text = label, FixedWidth = 130 } );

        var input = row.Add( new LineEdit( this ) );
        input.PlaceholderText = placeholder;
        StyleInput( input );
        return input;
    }

    private LineEdit AddIconRow(string label, string placeholder)
    {
        var row = Layout.AddRow();
        row.Spacing = 8f;
        row.Add( new Label( this ) { Text = label, FixedWidth = 130 } );

        var input = row.Add( new LineEdit( this ) );
        input.PlaceholderText = placeholder;
        StyleInput( input );

        var button = row.Add( new IconButton( "search", () => ShowIconPicker( input ), this ) );
        button.ToolTip = "Browse material icons";
        button.MinimumWidth = Theme.RowHeight;

        return input;
    }

    private LineEdit AddTextArea(string label, string placeholder)
    {
        var column = Layout.Add( Layout.Column() );
        column.Spacing = 4f;
        column.Add( new Label( this ) { Text = label } );

        var input = column.Add( new LineEdit( this ) );
        input.PlaceholderText = placeholder;
        StyleInput( input );
        return input;
    }

    private void Submit()
    {
        var name = _nameInput.Text?.Trim();
        if ( string.IsNullOrWhiteSpace( name ) )
        {
            EditorUtility.DisplayDialog( "Missing Title", "Please enter a title for the bookmark." );
            return;
        }

        var icon = string.IsNullOrWhiteSpace( _iconInput.Text ) ? "extension" : _iconInput.Text.Trim();

        var definition = _initialDefinition is null
            ? new CustomLocationDefinition()
            : new CustomLocationDefinition { Id = _initialDefinition.Id };

        definition.Name = name;
        definition.Icon = icon;
        definition.AssetTypes = _assetTypeSelector.SelectedTags.Select( NormalizeExtension ).Where( x => !string.IsNullOrWhiteSpace( x ) ).ToList();
        definition.IncludeFolders = SplitToList( _includeInput.Text );
        definition.ExcludeFolders = SplitToList( _excludeInput.Text );
        definition.ProjectAssetsOnly = _projectOnlyToggle.Value;

        _onConfirm?.Invoke( definition );
        Close();
    }

    private void ShowIconPicker( LineEdit target )
    {
        var pickerType = AppDomain.CurrentDomain.GetAssemblies()
            .Select( asm => asm.GetType( "Editor.IconPickerWidget", false ) )
            .FirstOrDefault( t => t is not null );

        var openPopup = pickerType?.GetMethod( "OpenPopup", BindingFlags.Public | BindingFlags.Static );
        if ( openPopup is null )
        {
            EditorUtility.DisplayDialog( "Icon Picker", "Unable to locate the icon picker widget." );
            return;
        }

        openPopup.Invoke( null, new object[]
        {
            this,
            target.Text ?? string.Empty,
            (Action<string>)(value => target.Text = value)
        } );
    }

    private static List<string> SplitToList(string raw)
    {
        if ( string.IsNullOrWhiteSpace( raw ) )
            return new List<string>();

        return raw
            .Split( new[] { ';', ',', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries )
            .Select( part => part.Trim() )
            .Where( part => part.Length > 0 )
            .ToList();
    }

    private static string NormalizeExtension( string value )
    {
        if ( string.IsNullOrWhiteSpace( value ) )
            return string.Empty;

        return value.Trim().TrimStart( '.' ).ToLowerInvariant();
    }

    private static void StyleInput( LineEdit input )
    {
        var background = Theme.ControlBackground.Darken( 0.25f ).Hex;
        var border = Theme.Border.Hex;
        input.SetStyles( $"background-color: {background}; border-color: {border};" );
    }
}
global using Sandbox;
global using Editor;
global using System.Collections.Generic;
global using System.Linq;
using System;
using Sandbox;
using Sandbox.ui;

public sealed class SceneGrassComponent : Component
{
    public static bool EditorPainterActive { get; set; }

	public GrassRenderObject Renderer { get; private set; }

	[Property] public GrassDensityMapResource DensityMapResource { get; set; }

	[Property] public float ChunkSize { get; set; } = 256.0f;

	[Property] public int ChunkResolution { get; set; } = 64;

	[Property] public int RenderRadius { get; set; } = 6;

	[Property] public float StreamingRadius { get; set; } = 1536.0f;

	[Property] public float LodCutoff { get; set; } = 2048.0f;

	[Property] public float DistanceCutoff { get; set; } = 4096.0f;

	[Property] public float LodTransitionRange { get; set; } = 200.0f;

	[Property] public float DistanceTransitionRange { get; set; } = 200.0f;

	[Property] public float DisplacementStrength { get; set; } = 200.0f;

	[Property] public float TerrainProbeTop { get; set; } = 4096.0f;

	[Property] public float TerrainProbeBottom { get; set; } = -4096.0f;

	[Property] public float TerrainHeightOffset { get; set; } = 0.0f;

	[Property] public float GrassHeightPadding { get; set; } = 128.0f;

	[Property] public float FallbackHeight { get; set; } = 0.0f;

	[Property] public float InteractionStrength { get; set; } = 8.0f;

	[Property] public float InteractionStampRate { get; set; } = 36.0f;

	[Property] public float InteractionBendHoldDuration { get; set; } = 0.5f;

	[Property] public float InteractionDecayUpdateInterval { get; set; } = 0.05f;

	[Property] public float CutDuration { get; set; } = 8.0f;

	protected override void OnAwake()
	{
		base.OnAwake();

		using ( Scene.Push() )
		{
			Renderer = new GrassRenderObject( Scene.SceneWorld );

		}

		SyncRendererSettings();
	}

	private void SyncRendererSettings()
	{
		if ( Renderer == null )
			return;

		float streamingRadius = StreamingRadius;
		if ( EditorPainterActive )
			streamingRadius *= 10.0f;

		Renderer.ChunkSize = ChunkSize;
		Renderer.ChunkResolution = ChunkResolution;
		float requiredStreamingRadius = Math.Max( streamingRadius, Math.Max( LodCutoff, DistanceCutoff ) + ChunkSize );
		Renderer.RenderRadius = Math.Max( 1, MathX.CeilToInt( requiredStreamingRadius / Math.Max( ChunkSize, 0.001f ) ) );
		Renderer.LodCutoff = LodCutoff;
		Renderer.LodTransitionRange = LodTransitionRange;
		Renderer.DistanceTransitionRange = DistanceTransitionRange;
		Renderer.DistanceCutoff = DistanceCutoff;
		Renderer.DisplacementStrength = DisplacementStrength;
		Renderer.TerrainProbeTop = TerrainProbeTop;
		Renderer.TerrainProbeBottom = TerrainProbeBottom;
		Renderer.TerrainHeightOffset = TerrainHeightOffset;
		Renderer.GrassHeightPadding = GrassHeightPadding;
		Renderer.FallbackHeight = FallbackHeight;
		Renderer.InteractionStrength = InteractionStrength;
		Renderer.InteractionStampRate = InteractionStampRate;
		Renderer.InteractionBendHoldDuration = InteractionBendHoldDuration;
		Renderer.CutDuration = CutDuration;
		Renderer.InteractionDecayUpdateInterval = InteractionDecayUpdateInterval;
		Renderer.SetDensityResource( DensityMapResource );
		Renderer.CullingCamera = Scene.Camera;
}

	protected override void OnUpdate()
	{
		base.OnUpdate();

		UpdateRenderer();

	}

	private void UpdateRenderer()
	{
		if ( Renderer == null )
			return;

		if ( Scene.Camera == null )
			return;

		SyncRendererSettings();
		Renderer.SetDensityResource( DensityMapResource );
		Renderer.CullingCamera = Scene.Camera;
		Renderer.UpdateInteractionField( Scene.GetAllComponents<GrassInteractionSourceComponent>(), Time.Delta );

		Vector3 camPos = Scene.Camera.WorldPosition;

		Renderer.UpdateStreaming( camPos );

		Renderer.ProcessPendingDestroy();
	}

	protected override void OnDisabled()
	{
		base.OnDisabled();

		Renderer?.Disable();

		Renderer = null;
	}

	protected override void DrawGizmos()
	{
		base.DrawGizmos();

		UpdateRenderer();

		if ( !EditorPainterActive )
			return;

		if ( Renderer == null )
			return;

		Gizmo.Draw.Color = Color.Yellow;

		foreach ( var pair in Renderer.ActiveChunks )
		{
			BBox bounds = BBox.FromPositionAndSize( pair.Value.Bounds.Center, pair.Value.Bounds.Size.WithZ( 0 ) );
			Gizmo.Draw.LineBBox( bounds );
		}
	}
}
using System;
using System.Collections.Generic;
using System.Text;

namespace Saandy.Tilemapper;

public interface ITilemapSceneEvent : ISceneEvent<ITilemapSceneEvent>
{

	/// <summary>
	/// Called when tilemap was changed this frame.
	/// </summary>
	void OnTilemapChanged() { }

	/// <summary>
	/// Called when the tilemap has been updated recently and stopped being updated.
	/// </summary>
	void OnTilemapStable() { }
}
using PanelRenderTarget;
using Sandbox;
using Sandbox.UI;
using System;
using System.Linq;

public class TargetScreen : Component, Component.DontExecuteOnServer, ITargetScreen
{
	[Property, Feature( "interaction" ), Description( "Enable verbose logs for screen mouse detection" )]
	public bool DebugMouseTrace { get; set; } = false;

	[Property] public string ScreenMaterialName { get; set; } = "screen-01";
	[Property] public Material ScreenMaterial { get; set; } = Material.Load( "materials/screen.vmat" );
	[Property] public Vector2Int ScreenTextureSize { get; set; } = new( 1280, 720 );
	[Property] public float TraceDistance { get; set; } = 200f;
	[Property] public bool ForceUpdate { get; set; } = false;
	[Property] public PanelTypeReference PanelType { get; set; } = new();
	[Property, Feature( "interaction" ), Description( "Small UV offset applied after triangle interpolation to correct slight drift" )]
	public Vector2 ScreenUvOffset { get; set; } = Vector2.Zero;

	[Property, Feature("interaction"), Description("interact with 2d mouse cursor")]
	public bool ScreenCursorInteraction { get; set; } = false;

	[Property,Feature("interaction"), Description("whether to show the virtual cursor") ]
	public bool ShowVirtualCursor { get; set; } = true;

	[Property, Feature( "Optimisation" ), Description("fps when the panel is focused") ]
	public int UpdateRateFocus { get; set; } = 60;

	[Property, Feature("Optimisation")]
	public bool UpdateWhenNotFocused { get; set; } = false;

	[Property, Feature( "Optimisation" ), Description( "fps update rate when the panel is visible in camera" ) ]
	public int UpdateRateNotFocused { get; set; } = 30;

	[Property, Feature( "Optimisation" ), Description("the distance of the update rate visible but not focus") ]
	public int UpdateDistanceMax { get; set; } = 500;


	private bool _firstUpdate = false;



	private readonly TargetPanelInput _input = new();

	public ModelRenderer Renderer { get; private set; }
	private Material _screenMaterialCopy;
	private Texture _screenTexture;
	private TargetRootPanel _rootPanel;
	private PanelSceneObject _panelObject;
	private Vertex[] _cachedVertices;
	private uint[] _cachedIndices;
	private Model _cachedMeshModel;
	private TriangleMaterialRange[] _cachedTriangleMaterialRanges = Array.Empty<TriangleMaterialRange>();
	private double _tracePerfAccumMs;
	private double _tracePerfMaxMs;
	private double _tracePerfCacheAccumMs;
	private double _tracePerfTrianglesAccumMs;
	private int _tracePerfSamples;
	private TimeSince _tracePerfLogTimer;

	private readonly struct TriangleMaterialRange
	{
		public int StartTriangle { get; init; }
		public int EndTriangleExclusive { get; init; }
		public Material Material { get; init; }
	}

	protected Panel Panel { get; private set; }
	public TargetRootPanel RootPanel => _rootPanel;
	public PanelSceneObject PanelObject => _panelObject;
	protected Texture ScreenTexture => _screenTexture;

	protected override void OnPreRender()
	{
		//ensure sceneobject have transform and correct bound for engine culling
		_panelObject.Transform = Renderer.Transform.World;
		_panelObject.Bounds = Renderer.Bounds;
	}

	protected override void OnEnabled()
	{
		base.OnEnabled();

		Renderer = Components.Get<ModelRenderer>();

		if ( !Renderer.IsValid() )
		{
			Log.Warning( "No ModelRenderer found." );
			Enabled = false;
			return;
		}

		RefreshMeshCache();
		CreateTexture();
		CreatePanel();
		SetupMaterial();
		CreatePanelObject();

		OnPanelCreated( Panel );

		var panelComponent = Components.Get<PanelComponent>();
		TargetPanelSystem.Current.RegisterScreen( this );
	}

	public Panel GetPanel()
	{
		return Panel;
	}

	protected virtual void OnPanelCreated( Panel panel )
	{
	}

	private void CreateTexture()
	{
		_screenTexture = Texture.CreateRenderTarget()
			.WithSize( ScreenTextureSize.x, ScreenTextureSize.y )
			.WithInitialColor( Color.Black )
			.WithMips()
			.Create();
	}

	private void CreatePanel()
	{
		var bounds = new Rect( 0, 0, ScreenTextureSize.x, ScreenTextureSize.y );

		_rootPanel = new TargetRootPanel
		{
			RenderedManually = true,
			FixedBounds = bounds,
			FixedScale = 1f,
			PanelBounds = bounds,
			MouseVisibility = ScreenCursorInteraction ? MouseVisibility.Visible : MouseVisibility.Hidden
		};

		_rootPanel.Style.Width = Length.Pixels( ScreenTextureSize.x );
		_rootPanel.Style.Height = Length.Pixels( ScreenTextureSize.y );

		var type = PanelType?.Resolve();

		if ( type?.TargetType is null || !typeof( Panel ).IsAssignableFrom( type.TargetType ) )
		{
			Log.Warning( $"Invalid panel type: {PanelType?.TypeName}" );
			return;
		}

		Panel = type.Create<Panel>();
		_rootPanel.AddChild( Panel );

		Panel.Style.Width = Length.Percent( 100 );
		Panel.Style.Height = Length.Percent( 100 );
	}

	private void CreatePanelObject()
	{
		_panelObject = new PanelSceneObject(
			GameObject.GetBounds(),
			Scene.SceneWorld,
			_rootPanel,
			_screenTexture,
			this
		);
	}

	public void Tick()
	{
		if ( !Renderer.IsValid() || Renderer.Model is null || !Panel.IsValid() )
			return;

		var camera = Scene.Camera;

		if ( camera is null )
			return;

		if ( !TryGetPanelPosition( camera, out var panelPos ) )
		{
			ClearInput();
			return;
		}

		_panelObject.CursorPosition = panelPos;
		
		_input.Tick(
			_rootPanel,
			panelPos,
			Input.Down( "attack1" ),
			Input.MouseWheel
		);

	}


	private bool TryGetPanelPosition( CameraComponent camera, out Vector2 panelPos )
	{
		panelPos = default;
		
		var screenCenter = new Vector2(
			camera.ScreenRect.Size.x * 0.5f,
			camera.ScreenRect.Size.y * 0.5f
		);

		var ray = camera.ScreenPixelToRay( screenCenter );

		if( ScreenCursorInteraction )
		{
			ray = camera.ScreenPixelToRay( Mouse.Position );
		}

		return TryGetPanelPositionFromMeshRaycast( ray, out panelPos );
	}

	private bool TryGetPanelPositionFromMeshRaycast( Ray ray, out Vector2 panelPos )
	{
		using var scope = Sandbox.Diagnostics.Performance.Scope( "TargetScreen.MouseTrace" );
		var totalTimer = Sandbox.Diagnostics.FastTimer.StartNew();
		panelPos = default;

		var cacheTimer = Sandbox.Diagnostics.FastTimer.StartNew();
		RefreshMeshCache();
		var cacheMs = cacheTimer.ElapsedMilliSeconds;

		if ( _cachedVertices is null || _cachedIndices is null || _cachedIndices.Length < 3 )
		{
			if ( DebugMouseTrace )
				Log.Info( $"[TargetScreen] Reject mesh cache: vertices={_cachedVertices?.Length ?? 0} indices={_cachedIndices?.Length ?? 0}" );
			UpdateDebugTracePerf( totalTimer.ElapsedMilliSeconds, cacheMs, 0f );
			return false;
		}

		var localOrigin = Renderer.Transform.World.PointToLocal( ray.Position );
		var localEnd = Renderer.Transform.World.PointToLocal( ray.Position + ray.Forward * TraceDistance );
		var localDirection = (localEnd - localOrigin).Normal;

		var bestDistance = float.MaxValue;
		var bestUv = Vector2.Zero;
		var bestTriangle = -1;
		var triangleTimer = Sandbox.Diagnostics.FastTimer.StartNew();

		for ( int triStart = 0; triStart + 2 < _cachedIndices.Length; triStart += 3 )
		{
			var triangleIndex = triStart / 3;
			if ( !IsTriangleMaterialMatch( triangleIndex ) )
				continue;

			var i0 = _cachedIndices[triStart + 0];
			var i1 = _cachedIndices[triStart + 1];
			var i2 = _cachedIndices[triStart + 2];
			if ( i0 >= _cachedVertices.Length || i1 >= _cachedVertices.Length || i2 >= _cachedVertices.Length )
				continue;

			var v0 = _cachedVertices[i0];
			var v1 = _cachedVertices[i1];
			var v2 = _cachedVertices[i2];

			if ( !TryRayTriangleIntersection( localOrigin, localDirection, v0.Position, v1.Position, v2.Position, out var distance, out var barycentric ) )
				continue;

			if ( distance > TraceDistance || distance >= bestDistance )
				continue;

			var triangleUv =
				v0.TexCoord0 * barycentric.x +
				v1.TexCoord0 * barycentric.y +
				v2.TexCoord0 * barycentric.z;

			bestDistance = distance;
			bestUv = triangleUv;
			bestTriangle = triangleIndex;
		}

		var triangleMs = triangleTimer.ElapsedMilliSeconds;

		if ( bestTriangle < 0 )
		{
			if ( DebugMouseTrace )
				Log.Info( $"[TargetScreen] No triangle hit. vertices={_cachedVertices.Length} indices={_cachedIndices.Length}" );
			UpdateDebugTracePerf( totalTimer.ElapsedMilliSeconds, cacheMs, triangleMs );
			return false;
		}

		if ( DebugMouseTrace )
			Log.Info( $"[TargetScreen] Mesh hit triangle={bestTriangle} distance={bestDistance} rawUv={bestUv}" );

		var uv = new Vector2(
			bestUv.x - MathF.Floor( bestUv.x ),
			bestUv.y - MathF.Floor( bestUv.y )
		);

		uv += ScreenUvOffset;

		panelPos = new Vector2(
			Math.Clamp( uv.x, 0f, 1f ) * ScreenTextureSize.x,
			Math.Clamp( uv.y, 0f, 1f ) * ScreenTextureSize.y
		);

		if ( DebugMouseTrace )
			Log.Info( $"[TargetScreen] Final UV={uv} panelPos={panelPos}" );

		UpdateDebugTracePerf( totalTimer.ElapsedMilliSeconds, cacheMs, triangleMs );
		return true;
	}

	private void UpdateDebugTracePerf( double totalMs, double cacheMs, double triangleMs )
	{
		_tracePerfAccumMs += totalMs;
		_tracePerfCacheAccumMs += cacheMs;
		_tracePerfTrianglesAccumMs += triangleMs;
		_tracePerfMaxMs = Math.Max( _tracePerfMaxMs, totalMs );
		_tracePerfSamples++;

		if ( _tracePerfLogTimer < 5f )
			return;

		var avgTotalMs = _tracePerfSamples > 0 ? _tracePerfAccumMs / _tracePerfSamples : 0d;
		var avgCacheMs = _tracePerfSamples > 0 ? _tracePerfCacheAccumMs / _tracePerfSamples : 0d;
		var avgTrianglesMs = _tracePerfSamples > 0 ? _tracePerfTrianglesAccumMs / _tracePerfSamples : 0d;
		var callsPerSecond = _tracePerfLogTimer > 0f ? _tracePerfSamples / _tracePerfLogTimer : 0f;
		var triangleCount = _cachedIndices?.Length / 3 ?? 0;

		Log.Info( $"[TargetScreen] Trace perf avg={avgTotalMs:F3}ms max={_tracePerfMaxMs:F3}ms cache={avgCacheMs:F3}ms triangles={avgTrianglesMs:F3}ms calls={callsPerSecond:F1}/s tris={triangleCount}" );

		_tracePerfAccumMs = 0d;
		_tracePerfCacheAccumMs = 0d;
		_tracePerfTrianglesAccumMs = 0d;
		_tracePerfMaxMs = 0d;
		_tracePerfSamples = 0;
		_tracePerfLogTimer = 0f;
	}

	private void RefreshMeshCache()
	{
		var model = Renderer?.Model;
		if ( model is null || model == _cachedMeshModel )
			return;

		_cachedMeshModel = model;
		_cachedVertices = model.GetVertices();
		_cachedIndices = model.GetIndices();
		_cachedTriangleMaterialRanges = BuildTriangleMaterialRanges( model );

		if ( DebugMouseTrace )
			Log.Info( $"[TargetScreen] Refreshed mesh cache for {model.Name}: vertices={_cachedVertices?.Length ?? 0} indices={_cachedIndices?.Length ?? 0} materialRanges={_cachedTriangleMaterialRanges.Length}" );
	}

	private TriangleMaterialRange[] BuildTriangleMaterialRanges( Model model )
	{
		var meshInfo = model.MeshInfo;
		if ( meshInfo?.Meshes is null )
			return Array.Empty<TriangleMaterialRange>();

		var ranges = new System.Collections.Generic.List<TriangleMaterialRange>();
		var triangleCursor = 0;

		foreach ( var mesh in meshInfo.Meshes )
		{
			if ( mesh?.DrawCalls is null )
				continue;

			foreach ( var drawCall in mesh.DrawCalls )
			{
				var triangleCount = Math.Max( 0, drawCall.Indices / 3 );
				if ( triangleCount == 0 )
					continue;

				ranges.Add( new TriangleMaterialRange
				{
					StartTriangle = triangleCursor,
					EndTriangleExclusive = triangleCursor + triangleCount,
					Material = drawCall.Material
				} );

				if ( DebugMouseTrace )
					Log.Info( $"[TargetScreen] Material range {triangleCursor}->{triangleCursor + triangleCount} material={drawCall.Material?.Name}" );

				triangleCursor += triangleCount;
			}
		}

		return ranges.ToArray();
	}

	private bool IsTriangleMaterialMatch( int triangleIndex )
	{
		if ( string.IsNullOrWhiteSpace( ScreenMaterialName ) || _cachedTriangleMaterialRanges.Length == 0 )
			return true;

		foreach ( var range in _cachedTriangleMaterialRanges )
		{
			if ( triangleIndex < range.StartTriangle || triangleIndex >= range.EndTriangleExclusive )
				continue;

			var match = range.Material?.Name?.Contains( ScreenMaterialName, StringComparison.OrdinalIgnoreCase ) == true;
			if ( DebugMouseTrace && triangleIndex == range.StartTriangle )
				Log.Info( $"[TargetScreen] Triangle {triangleIndex} material={range.Material?.Name} match={match}" );
			return match;
		}

		return true;
	}

	private static bool TryRayTriangleIntersection( Vector3 origin, Vector3 direction, Vector3 a, Vector3 b, Vector3 c, out float distance, out Vector3 barycentric )
	{
		distance = 0f;
		barycentric = default;

		const float epsilon = 0.0001f;
		var edge1 = b - a;
		var edge2 = c - a;
		var pvec = Vector3.Cross( direction, edge2 );
		var det = Vector3.Dot( edge1, pvec );
		if ( MathF.Abs( det ) < epsilon )
			return false;

		var invDet = 1f / det;
		var tvec = origin - a;
		var v = Vector3.Dot( tvec, pvec ) * invDet;
		if ( v < 0f || v > 1f )
			return false;

		var qvec = Vector3.Cross( tvec, edge1 );
		var w = Vector3.Dot( direction, qvec ) * invDet;
		if ( w < 0f || v + w > 1f )
			return false;

		distance = Vector3.Dot( edge2, qvec ) * invDet;
		if ( distance < 0f )
			return false;

		barycentric = new Vector3( 1f - v - w, v, w );
		return true;
	}

	private void SetupMaterial()
	{
		var oldMaterial = Renderer.Model.Materials
			.FirstOrDefault( x => x.Name.Contains( ScreenMaterialName ) );

		var index = Renderer.Model.Materials.IndexOf( oldMaterial );

		if ( index < 0 )
		{
			Log.Warning( $"Screen material not found: {ScreenMaterialName}" );
			return;
		}

		_screenMaterialCopy = ScreenMaterial.CreateCopy();
		_screenMaterialCopy.Set( "g_tColor", _screenTexture );

		Renderer.Materials.SetOverride( index, _screenMaterialCopy );
	}

	private void ClearInput()
	{
		_input.Clear();
	}

	protected override void OnDisabled()
	{
		base.OnDisabled();

		ClearInput();

		_panelObject?.Delete();
		_panelObject = null;

		_rootPanel?.Delete( true );
		_rootPanel = null;

		_screenTexture?.Dispose();
		_screenTexture = null;

		_screenMaterialCopy = null;
		Panel = null;
		Renderer = null;

		TargetPanelSystem.Current.UnregisterScreen( this );
	}
}
using Sandbox;

[TestClass]
public partial class LibraryTests
{
	[TestMethod]
	public void SceneTest()
	{
		var scene = new Scene();
		using ( scene.Push() )
		{
			var go = new GameObject();

			Assert.AreEqual( 1, scene.Directory.GameObjectCount );
		}
	}

}
global using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class TestInit
{
	public static Sandbox.TestAppSystem AppSystem;

	[AssemblyInitialize]
	public static void AssemblyInitialize( TestContext context )
	{
		AppSystem = new Sandbox.TestAppSystem();
		AppSystem.Init();
	}

	[AssemblyCleanup]
	public static void AssemblyCleanup()
	{
		AppSystem.Shutdown();
	}
}
using System;
using Sandbox;

namespace Goo.Animation;

public record struct SmoothVector2
{
    public Vector2 Current;
    public Vector2 Target;
    public Vector2 Velocity;
    public float SmoothTime;

    public SmoothVector2(Vector2 initial, float smoothTime)
    {
        Current = initial;
        Target = initial;
        Velocity = default;
        SmoothTime = smoothTime;
    }

    public void Update(float dt)
    {
        float vx = Velocity.x, vy = Velocity.y;
        Current = new Vector2(
            MathX.SmoothDamp(Current.x, Target.x, ref vx, SmoothTime, dt),
            MathX.SmoothDamp(Current.y, Target.y, ref vy, SmoothTime, dt));
        Velocity = new Vector2(vx, vy);
    }

    public bool IsSettled =>
        MathF.Abs(Target.x - Current.x) < 0.0001f &&
        MathF.Abs(Target.y - Current.y) < 0.0001f &&
        MathF.Abs(Velocity.x) < 0.0001f &&
        MathF.Abs(Velocity.y) < 0.0001f;

    /// <summary>Advances by dt and returns true while still moving; chain calls with | (not ||) so every damper advances each frame.</summary>
    public bool Tick(float dt) { Update(dt); return !IsSettled; }
}
using System;

namespace Goo.Animation;

public readonly record struct Tween
{
    public Sandbox.Utility.Easing.Function Easing { get; init; }
    public float Duration   { get; init; }
    public float Delay      { get; init; }
    public float SpeedScale { get; init; }
    public int   Iterations { get; init; }
    public bool  PingPong   { get; init; }
    public bool  Reversed   { get; init; }

    public Tween(Sandbox.Utility.Easing.Function easing, float duration, float delay = 0f)
    {
        Easing     = easing;
        Duration   = duration;
        Delay      = delay;
        SpeedScale = 1f;
        Iterations = 1;
        PingPong   = false;
        Reversed   = false;
    }

    /// <summary>
    /// Bridge a designer-authored Sandbox.Curve (authored over [0, 1]) into a Tween.
    /// Allocates one delegate per call; cache the result in a static readonly field.
    /// </summary>
    public static Tween FromCurve(Sandbox.Curve curve, float duration, float delay = 0f)
        => new Tween(curve.Evaluate, duration, delay);

    public float Eval(float elapsedSec)
    {
        if (Duration <= 0f) return Reversed ? 0f : 1f;

        float t = (elapsedSec - Delay) * SpeedScale;
        if (t <= 0f) return Reversed ? 1f : 0f;

        float cycleDuration = PingPong ? 2f * Duration : Duration;

        if (Iterations > 0 && t >= cycleDuration * Iterations)
        {
            float endLocal = PingPong ? 0f : 1f;
            if (Reversed) endLocal = 1f - endLocal;
            return Easing(endLocal);
        }

        float cycleT = t % cycleDuration;
        float local = PingPong
            ? (cycleT < Duration ? cycleT / Duration : 1f - (cycleT - Duration) / Duration)
            : cycleT / Duration;

        if (Reversed) local = 1f - local;
        return Easing(local);
    }
}

public static class TweenExtensions
{
    public static Tween Loop(this Tween t)               => t with { Iterations = -1 };
    public static Tween Times(this Tween t, int n)       => t with { Iterations = n };
    public static Tween PingPong(this Tween t)           => t with { PingPong = true };
    public static Tween Scale(this Tween t, float speed) => t with { SpeedScale = speed };
    public static Tween WithDelay(this Tween t, float s) => t with { Delay = s };
    public static Tween Reverse(this Tween t)            => t with { Reversed = true };
}
using System;
using System.Collections;

namespace Goo;

public sealed class Children : IEnumerable
{
    internal FrameList? _list;
    internal int _buildId;
    internal Children() { }
    internal int Count { get { EnsureValid(); return _list!.Count; } }
    internal ref Frame this[int i] { get { EnsureValid(); return ref _list![i]; } }

    public void Add<T>(in T child) where T : struct, IBlob
    {
        EnsureValid();
        ref Frame slot = ref _list!.Reserve();
        child.WriteTo(ref slot);
    }

    void EnsureValid()
    {
        var ctx = BuildContext._current;
        if (ctx == null || _list == null || _buildId != ctx._currentBuildId)
            throw new InvalidOperationException(
                "Container reused across rebuilds. The same Container instance cannot survive " +
                "past the Build() it was created in. Build a new one inside Build(), or extract " +
                "a helper function that returns a fresh Container each call.");
    }

    // IEnumerable is required by C# collection-initializer syntax; iteration is not a
    // use case for Children, so this returns an empty enumerator.
    IEnumerator IEnumerable.GetEnumerator() => Array.Empty<object>().GetEnumerator();
}

namespace Goo;

/// <summary>Compile-time constraint for blob struct types. Never use as storage, return, or parameter type (boxes the struct, destroys per-Rebuild allocation profile); only valid in where T : struct, IBlob.</summary>
public interface IBlob
{
    static abstract BlobKind Kind { get; }
    string? Key { get; }
    internal void WriteTo(ref Frame frame);
}

/// <summary>Returns the single root Blob for a GooView build. A named delegate rather than
/// Func&lt;IBlob&gt; because IBlob has a static-abstract member (Kind) and C# bars such interfaces
/// as generic type arguments (CS8920). Consequence for Razor markup: a bare method group cannot
/// bind (its natural type is the illegal Func&lt;IBlob&gt;), so write
/// <c>Build=@(new BlobBuilder(MyBuild))</c>. See docs/site/docs/gotchas.md.</summary>
public delegate IBlob BlobBuilder();
// <auto-generated />
// Generated by tools/StyleFacadeEmit. Do not edit by hand.
// Source of truth: tools/StyleFacadeEmit/style-manifest.json
using Sandbox;
using Sandbox.Rendering;
using Sandbox.UI;

namespace Goo;

public readonly partial record struct Text
{
    public Length? Width { init => _style = StyleAccumulator.Add(_style, StyleField.Width, value); }
    public Length? Height { init => _style = StyleAccumulator.Add(_style, StyleField.Height, value); }
    public Length? Margin { init => _style = StyleAccumulator.Add(_style, StyleField.Margin, value); }
    public Length? MarginLeft { init => _style = StyleAccumulator.Add(_style, StyleField.MarginLeft, value); }
    public Length? MarginTop { init => _style = StyleAccumulator.Add(_style, StyleField.MarginTop, value); }
    public Length? MarginRight { init => _style = StyleAccumulator.Add(_style, StyleField.MarginRight, value); }
    public Length? MarginBottom { init => _style = StyleAccumulator.Add(_style, StyleField.MarginBottom, value); }
    public Color? BackgroundColor { init => _style = StyleAccumulator.Add(_style, StyleField.BackgroundColor, value, StyleValue.FromColor); }
    public Color? BackgroundTint { init => _style = StyleAccumulator.Add(_style, StyleField.BackgroundTint, value, StyleValue.FromColor); }
    public Length? FlexBasis { init => _style = StyleAccumulator.Add(_style, StyleField.FlexBasis, value); }
    public float? FlexGrow { init => _style = StyleAccumulator.Add(_style, StyleField.FlexGrow, value); }
    public float? FlexShrink { init => _style = StyleAccumulator.Add(_style, StyleField.FlexShrink, value); }
    public Color? FontColor { init => _style = StyleAccumulator.Add(_style, StyleField.FontColor, value, StyleValue.FromColor); }
    public string? FontFamily { init => _style = StyleAccumulator.Add(_style, StyleField.FontFamily, value); }
    public Length? FontSize { init => _style = StyleAccumulator.Add(_style, StyleField.FontSize, value); }
    public FontSmooth? FontSmooth { init => _style = StyleAccumulator.Add(_style, StyleField.FontSmooth, value, StyleValue.FromFontSmooth); }
    public FontStyle? FontStyle { init => _style = StyleAccumulator.Add(_style, StyleField.FontStyle, value, StyleValue.FromFontStyle); }
    public FontVariantNumeric? FontVariantNumeric { init => _style = StyleAccumulator.Add(_style, StyleField.FontVariantNumeric, value, StyleValue.FromFontVariantNumeric); }
    public int? FontWeight { init => _style = StyleAccumulator.Add(_style, StyleField.FontWeight, value); }
    public Length? LetterSpacing { init => _style = StyleAccumulator.Add(_style, StyleField.LetterSpacing, value); }
    public Length? LineHeight { init => _style = StyleAccumulator.Add(_style, StyleField.LineHeight, value); }
    public Length? MaxHeight { init => _style = StyleAccumulator.Add(_style, StyleField.MaxHeight, value); }
    public Length? MaxWidth { init => _style = StyleAccumulator.Add(_style, StyleField.MaxWidth, value); }
    public Length? MinHeight { init => _style = StyleAccumulator.Add(_style, StyleField.MinHeight, value); }
    public Length? MinWidth { init => _style = StyleAccumulator.Add(_style, StyleField.MinWidth, value); }
    public float? Opacity { init => _style = StyleAccumulator.Add(_style, StyleField.Opacity, value); }
    public TextAlign? TextAlign { init => _style = StyleAccumulator.Add(_style, StyleField.TextAlign, value, StyleValue.FromTextAlign); }
    public Length? TextBackgroundAngle { init => _style = StyleAccumulator.Add(_style, StyleField.TextBackgroundAngle, value); }
    public Color? TextDecorationColor { init => _style = StyleAccumulator.Add(_style, StyleField.TextDecorationColor, value, StyleValue.FromColor); }
    public TextDecoration? TextDecorationLine { init => _style = StyleAccumulator.Add(_style, StyleField.TextDecorationLine, value, StyleValue.FromTextDecoration); }
    public TextSkipInk? TextDecorationSkipInk { init => _style = StyleAccumulator.Add(_style, StyleField.TextDecorationSkipInk, value, StyleValue.FromTextSkipInk); }
    public TextDecorationStyle? TextDecorationStyle { init => _style = StyleAccumulator.Add(_style, StyleField.TextDecorationStyle, value, StyleValue.FromTextDecorationStyle); }
    public Length? TextDecorationThickness { init => _style = StyleAccumulator.Add(_style, StyleField.TextDecorationThickness, value); }
    public FilterMode? TextFilter { init => _style = StyleAccumulator.Add(_style, StyleField.TextFilter, value, StyleValue.FromFilterMode); }
    public Length? TextLineThroughOffset { init => _style = StyleAccumulator.Add(_style, StyleField.TextLineThroughOffset, value); }
    public TextOverflow? TextOverflow { init => _style = StyleAccumulator.Add(_style, StyleField.TextOverflow, value, StyleValue.FromTextOverflow); }
    public Length? TextOverlineOffset { init => _style = StyleAccumulator.Add(_style, StyleField.TextOverlineOffset, value); }
    public Color? TextStrokeColor { init => _style = StyleAccumulator.Add(_style, StyleField.TextStrokeColor, value, StyleValue.FromColor); }
    public Length? TextStrokeWidth { init => _style = StyleAccumulator.Add(_style, StyleField.TextStrokeWidth, value); }
    public TextTransform? TextTransform { init => _style = StyleAccumulator.Add(_style, StyleField.TextTransform, value, StyleValue.FromTextTransform); }
    public Length? TextUnderlineOffset { init => _style = StyleAccumulator.Add(_style, StyleField.TextUnderlineOffset, value); }
    public Goo.PanelTransform? Transform { init => _style = StyleAccumulator.Add(_style, StyleField.Transform, value, StyleValue.FromPanelTransform); }
    public WhiteSpace? WhiteSpace { init => _style = StyleAccumulator.Add(_style, StyleField.WhiteSpace, value, StyleValue.FromWhiteSpace); }
    public WordBreak? WordBreak { init => _style = StyleAccumulator.Add(_style, StyleField.WordBreak, value, StyleValue.FromWordBreak); }
    public Length? WordSpacing { init => _style = StyleAccumulator.Add(_style, StyleField.WordSpacing, value); }
    public Color? HoverBackgroundColor { init => _style = StyleAccumulator.Add(_style, StyleField.HoverBackgroundColor, value, StyleValue.FromColor); }
    public Color? ActiveBackgroundColor { init => _style = StyleAccumulator.Add(_style, StyleField.ActiveBackgroundColor, value, StyleValue.FromColor); }
    public Color? FocusBackgroundColor { init => _style = StyleAccumulator.Add(_style, StyleField.FocusBackgroundColor, value, StyleValue.FromColor); }
    public Color? HoverFontColor { init => _style = StyleAccumulator.Add(_style, StyleField.HoverFontColor, value, StyleValue.FromColor); }
    public Color? ActiveFontColor { init => _style = StyleAccumulator.Add(_style, StyleField.ActiveFontColor, value, StyleValue.FromColor); }
    public Color? FocusFontColor { init => _style = StyleAccumulator.Add(_style, StyleField.FocusFontColor, value, StyleValue.FromColor); }
    public int? TransitionMs { init => _style = StyleAccumulator.Add(_style, StyleField.TransitionMs, value); }
}
// <auto-generated />
// Generated by tools/StyleFacadeEmit. Do not edit by hand.
// Source of truth: tools/StyleFacadeEmit/style-manifest.json
using Sandbox;
using Sandbox.Rendering;
using Sandbox.UI;

namespace Goo;

public readonly partial record struct TextEntry
{
    public FlexDirection? FlexDirection { init => _style = StyleAccumulator.Add(_style, StyleField.FlexDirection, value, StyleValue.FromFlexDirection); }
    public Justify? JustifyContent { init => _style = StyleAccumulator.Add(_style, StyleField.JustifyContent, value, StyleValue.FromJustify); }
    public Align? AlignItems { init => _style = StyleAccumulator.Add(_style, StyleField.AlignItems, value, StyleValue.FromAlign); }
    public DisplayMode? Display { init => _style = StyleAccumulator.Add(_style, StyleField.Display, value, StyleValue.FromDisplay); }
    public Length? Width { init => _style = StyleAccumulator.Add(_style, StyleField.Width, value); }
    public Length? Height { init => _style = StyleAccumulator.Add(_style, StyleField.Height, value); }
    public Length? Padding { init => _style = StyleAccumulator.Add(_style, StyleField.Padding, value); }
    public Length? PaddingLeft { init => _style = StyleAccumulator.Add(_style, StyleField.PaddingLeft, value); }
    public Length? PaddingTop { init => _style = StyleAccumulator.Add(_style, StyleField.PaddingTop, value); }
    public Length? PaddingRight { init => _style = StyleAccumulator.Add(_style, StyleField.PaddingRight, value); }
    public Length? PaddingBottom { init => _style = StyleAccumulator.Add(_style, StyleField.PaddingBottom, value); }
    public Length? Margin { init => _style = StyleAccumulator.Add(_style, StyleField.Margin, value); }
    public Length? MarginLeft { init => _style = StyleAccumulator.Add(_style, StyleField.MarginLeft, value); }
    public Length? MarginTop { init => _style = StyleAccumulator.Add(_style, StyleField.MarginTop, value); }
    public Length? MarginRight { init => _style = StyleAccumulator.Add(_style, StyleField.MarginRight, value); }
    public Length? MarginBottom { init => _style = StyleAccumulator.Add(_style, StyleField.MarginBottom, value); }
    public Length? Gap { init => _style = StyleAccumulator.Add(_style, StyleField.Gap, value); }
    public Length? RowGap { init => _style = StyleAccumulator.Add(_style, StyleField.RowGap, value); }
    public Length? ColumnGap { init => _style = StyleAccumulator.Add(_style, StyleField.ColumnGap, value); }
    public Color? BackgroundColor { init => _style = StyleAccumulator.Add(_style, StyleField.BackgroundColor, value, StyleValue.FromColor); }
    public Length? BorderRadius { init => _style = StyleAccumulator.Add(_style, StyleField.BorderRadius, value); }
    public Length? BorderTopLeftRadius { init => _style = StyleAccumulator.Add(_style, StyleField.BorderTopLeftRadius, value); }
    public Length? BorderTopRightRadius { init => _style = StyleAccumulator.Add(_style, StyleField.BorderTopRightRadius, value); }
    public Length? BorderBottomRightRadius { init => _style = StyleAccumulator.Add(_style, StyleField.BorderBottomRightRadius, value); }
    public Length? BorderBottomLeftRadius { init => _style = StyleAccumulator.Add(_style, StyleField.BorderBottomLeftRadius, value); }
    public Align? AlignContent { init => _style = StyleAccumulator.Add(_style, StyleField.AlignContent, value, StyleValue.FromAlign); }
    public Align? AlignSelf { init => _style = StyleAccumulator.Add(_style, StyleField.AlignSelf, value, StyleValue.FromAlign); }
    public float? AspectRatio { init => _style = StyleAccumulator.Add(_style, StyleField.AspectRatio, value); }
    public Length? BackdropFilterBlur { init => _style = StyleAccumulator.Add(_style, StyleField.BackdropFilterBlur, value); }
    public Length? BackdropFilterBrightness { init => _style = StyleAccumulator.Add(_style, StyleField.BackdropFilterBrightness, value); }
    public Length? BackdropFilterContrast { init => _style = StyleAccumulator.Add(_style, StyleField.BackdropFilterContrast, value); }
    public Length? BackdropFilterHueRotate { init => _style = StyleAccumulator.Add(_style, StyleField.BackdropFilterHueRotate, value); }
    public Length? BackdropFilterInvert { init => _style = StyleAccumulator.Add(_style, StyleField.BackdropFilterInvert, value); }
    public Length? BackdropFilterSaturate { init => _style = StyleAccumulator.Add(_style, StyleField.BackdropFilterSaturate, value); }
    public Length? BackdropFilterSepia { init => _style = StyleAccumulator.Add(_style, StyleField.BackdropFilterSepia, value); }
    public Length? BackgroundAngle { init => _style = StyleAccumulator.Add(_style, StyleField.BackgroundAngle, value); }
    public string? BackgroundBlendMode { init => _style = StyleAccumulator.Add(_style, StyleField.BackgroundBlendMode, value); }
    public Texture? BackgroundImage { init => _style = StyleAccumulator.Add(_style, StyleField.BackgroundImage, value); }
    public bool? BackgroundPlaybackPaused { init => _style = StyleAccumulator.Add(_style, StyleField.BackgroundPlaybackPaused, value); }
    public Length? BackgroundPositionX { init => _style = StyleAccumulator.Add(_style, StyleField.BackgroundPositionX, value); }
    public Length? BackgroundPositionY { init => _style = StyleAccumulator.Add(_style, StyleField.BackgroundPositionY, value); }
    public BackgroundRepeat? BackgroundRepeat { init => _style = StyleAccumulator.Add(_style, StyleField.BackgroundRepeat, value, StyleValue.FromBackgroundRepeat); }
    public Length? BackgroundSizeX { init => _style = StyleAccumulator.Add(_style, StyleField.BackgroundSizeX, value); }
    public Length? BackgroundSizeY { init => _style = StyleAccumulator.Add(_style, StyleField.BackgroundSizeY, value); }
    public Color? BackgroundTint { init => _style = StyleAccumulator.Add(_style, StyleField.BackgroundTint, value, StyleValue.FromColor); }
    public Color? BorderBottomColor { init => _style = StyleAccumulator.Add(_style, StyleField.BorderBottomColor, value, StyleValue.FromColor); }
    public Color? BorderColor { init => _style = StyleAccumulator.Add(_style, StyleField.BorderColor, value, StyleValue.FromColor); }
    public Color? BorderLeftColor { init => _style = StyleAccumulator.Add(_style, StyleField.BorderLeftColor, value, StyleValue.FromColor); }
    public Color? BorderRightColor { init => _style = StyleAccumulator.Add(_style, StyleField.BorderRightColor, value, StyleValue.FromColor); }
    public Color? BorderTopColor { init => _style = StyleAccumulator.Add(_style, StyleField.BorderTopColor, value, StyleValue.FromColor); }
    public BorderImageFill? BorderImageFill { init => _style = StyleAccumulator.Add(_style, StyleField.BorderImageFill, value, StyleValue.FromBorderImageFill); }
    public BorderImageRepeat? BorderImageRepeat { init => _style = StyleAccumulator.Add(_style, StyleField.BorderImageRepeat, value, StyleValue.FromBorderImageRepeat); }
    public Texture? BorderImageSource { init => _style = StyleAccumulator.Add(_style, StyleField.BorderImageSource, value); }
    public Color? BorderImageTint { init => _style = StyleAccumulator.Add(_style, StyleField.BorderImageTint, value, StyleValue.FromColor); }
    public Length? BorderImageWidthBottom { init => _style = StyleAccumulator.Add(_style, StyleField.BorderImageWidthBottom, value); }
    public Length? BorderImageWidthLeft { init => _style = StyleAccumulator.Add(_style, StyleField.BorderImageWidthLeft, value); }
    public Length? BorderImageWidthRight { init => _style = StyleAccumulator.Add(_style, StyleField.BorderImageWidthRight, value); }
    public Length? BorderImageWidthTop { init => _style = StyleAccumulator.Add(_style, StyleField.BorderImageWidthTop, value); }
    public Length? BorderBottomWidth { init => _style = StyleAccumulator.Add(_style, StyleField.BorderBottomWidth, value); }
    public Length? BorderLeftWidth { init => _style = StyleAccumulator.Add(_style, StyleField.BorderLeftWidth, value); }
    public Length? BorderRightWidth { init => _style = StyleAccumulator.Add(_style, StyleField.BorderRightWidth, value); }
    public Length? BorderTopWidth { init => _style = StyleAccumulator.Add(_style, StyleField.BorderTopWidth, value); }
    public Length? BorderWidth { init => _style = StyleAccumulator.Add(_style, StyleField.BorderWidth, value); }
    public Length? Bottom { init => _style = StyleAccumulator.Add(_style, StyleField.Bottom, value); }
    public Length? Left { init => _style = StyleAccumulator.Add(_style, StyleField.Left, value); }
    public Length? Right { init => _style = StyleAccumulator.Add(_style, StyleField.Right, value); }
    public Length? Top { init => _style = StyleAccumulator.Add(_style, StyleField.Top, value); }
    public Color? CaretColor { init => _style = StyleAccumulator.Add(_style, StyleField.CaretColor, value, StyleValue.FromColor); }
    public string? Cursor { init => _style = StyleAccumulator.Add(_style, StyleField.Cursor, value); }
    public Length? FilterBlur { init => _style = StyleAccumulator.Add(_style, StyleField.FilterBlur, value); }
    public Color? FilterBorderColor { init => _style = StyleAccumulator.Add(_style, StyleField.FilterBorderColor, value, StyleValue.FromColor); }
    public Length? FilterBorderWidth { init => _style = StyleAccumulator.Add(_style, StyleField.FilterBorderWidth, value); }
    public Length? FilterBrightness { init => _style = StyleAccumulator.Add(_style, StyleField.FilterBrightness, value); }
    public Length? FilterContrast { init => _style = StyleAccumulator.Add(_style, StyleField.FilterContrast, value); }
    public Length? FilterHueRotate { init => _style = StyleAccumulator.Add(_style, StyleField.FilterHueRotate, value); }
    public Length? FilterInvert { init => _style = StyleAccumulator.Add(_style, StyleField.FilterInvert, value); }
    public Length? FilterSaturate { init => _style = StyleAccumulator.Add(_style, StyleField.FilterSaturate, value); }
    public Length? FilterSepia { init => _style = StyleAccumulator.Add(_style, StyleField.FilterSepia, value); }
    public Color? FilterTint { init => _style = StyleAccumulator.Add(_style, StyleField.FilterTint, value, StyleValue.FromColor); }
    public Length? FlexBasis { init => _style = StyleAccumulator.Add(_style, StyleField.FlexBasis, value); }
    public float? FlexGrow { init => _style = StyleAccumulator.Add(_style, StyleField.FlexGrow, value); }
    public float? FlexShrink { init => _style = StyleAccumulator.Add(_style, StyleField.FlexShrink, value); }
    public Wrap? FlexWrap { init => _style = StyleAccumulator.Add(_style, StyleField.FlexWrap, value, StyleValue.FromWrap); }
    public Color? FontColor { init => _style = StyleAccumulator.Add(_style, StyleField.FontColor, value, StyleValue.FromColor); }
    public string? FontFamily { init => _style = StyleAccumulator.Add(_style, StyleField.FontFamily, value); }
    public Length? FontSize { init => _style = StyleAccumulator.Add(_style, StyleField.FontSize, value); }
    public FontSmooth? FontSmooth { init => _style = StyleAccumulator.Add(_style, StyleField.FontSmooth, value, StyleValue.FromFontSmooth); }
    public FontStyle? FontStyle { init => _style = StyleAccumulator.Add(_style, StyleField.FontStyle, value, StyleValue.FromFontStyle); }
    public FontVariantNumeric? FontVariantNumeric { init => _style = StyleAccumulator.Add(_style, StyleField.FontVariantNumeric, value, StyleValue.FromFontVariantNumeric); }
    public int? FontWeight { init => _style = StyleAccumulator.Add(_style, StyleField.FontWeight, value); }
    public ImageRendering? ImageRendering { init => _style = StyleAccumulator.Add(_style, StyleField.ImageRendering, value, StyleValue.FromImageRendering); }
    public Length? LetterSpacing { init => _style = StyleAccumulator.Add(_style, StyleField.LetterSpacing, value); }
    public Length? LineHeight { init => _style = StyleAccumulator.Add(_style, StyleField.LineHeight, value); }
    public Length? MaskAngle { init => _style = StyleAccumulator.Add(_style, StyleField.MaskAngle, value); }
    public Texture? MaskImage { init => _style = StyleAccumulator.Add(_style, StyleField.MaskImage, value); }
    public MaskMode? MaskMode { init => _style = StyleAccumulator.Add(_style, StyleField.MaskMode, value, StyleValue.FromMaskMode); }
    public Length? MaskPositionX { init => _style = StyleAccumulator.Add(_style, StyleField.MaskPositionX, value); }
    public Length? MaskPositionY { init => _style = StyleAccumulator.Add(_style, StyleField.MaskPositionY, value); }
    public BackgroundRepeat? MaskRepeat { init => _style = StyleAccumulator.Add(_style, StyleField.MaskRepeat, value, StyleValue.FromBackgroundRepeat); }
    public MaskScope? MaskScope { init => _style = StyleAccumulator.Add(_style, StyleField.MaskScope, value, StyleValue.FromMaskScope); }
    public Length? MaskSizeX { init => _style = StyleAccumulator.Add(_style, StyleField.MaskSizeX, value); }
    public Length? MaskSizeY { init => _style = StyleAccumulator.Add(_style, StyleField.MaskSizeY, value); }
    public Length? MaxHeight { init => _style = StyleAccumulator.Add(_style, StyleField.MaxHeight, value); }
    public Length? MaxWidth { init => _style = StyleAccumulator.Add(_style, StyleField.MaxWidth, value); }
    public Length? MinHeight { init => _style = StyleAccumulator.Add(_style, StyleField.MinHeight, value); }
    public Length? MinWidth { init => _style = StyleAccumulator.Add(_style, StyleField.MinWidth, value); }
    public string? MixBlendMode { init => _style = StyleAccumulator.Add(_style, StyleField.MixBlendMode, value); }
    public float? Opacity { init => _style = StyleAccumulator.Add(_style, StyleField.Opacity, value); }
    public int? Order { init => _style = StyleAccumulator.Add(_style, StyleField.Order, value); }
    public Color? OutlineColor { init => _style = StyleAccumulator.Add(_style, StyleField.OutlineColor, value, StyleValue.FromColor); }
    public Length? OutlineOffset { init => _style = StyleAccumulator.Add(_style, StyleField.OutlineOffset, value); }
    public Length? OutlineWidth { init => _style = StyleAccumulator.Add(_style, StyleField.OutlineWidth, value); }
    public OverflowMode? Overflow { init => _style = StyleAccumulator.Add(_style, StyleField.Overflow, value, StyleValue.FromOverflowMode); }
    public OverflowMode? OverflowX { init => _style = StyleAccumulator.Add(_style, StyleField.OverflowX, value, StyleValue.FromOverflowMode); }
    public OverflowMode? OverflowY { init => _style = StyleAccumulator.Add(_style, StyleField.OverflowY, value, StyleValue.FromOverflowMode); }
    public Length? PerspectiveOriginX { init => _style = StyleAccumulator.Add(_style, StyleField.PerspectiveOriginX, value); }
    public Length? PerspectiveOriginY { init => _style = StyleAccumulator.Add(_style, StyleField.PerspectiveOriginY, value); }
    public PointerEvents? PointerEvents { init => _style = StyleAccumulator.Add(_style, StyleField.PointerEvents, value, StyleValue.FromPointerEvents); }
    public PositionMode? Position { init => _style = StyleAccumulator.Add(_style, StyleField.Position, value, StyleValue.FromPositionMode); }
    public string? SoundIn { init => _style = StyleAccumulator.Add(_style, StyleField.SoundIn, value); }
    public string? SoundOut { init => _style = StyleAccumulator.Add(_style, StyleField.SoundOut, value); }
    public TextAlign? TextAlign { init => _style = StyleAccumulator.Add(_style, StyleField.TextAlign, value, StyleValue.FromTextAlign); }
    public Length? TextBackgroundAngle { init => _style = StyleAccumulator.Add(_style, StyleField.TextBackgroundAngle, value); }
    public Color? TextDecorationColor { init => _style = StyleAccumulator.Add(_style, StyleField.TextDecorationColor, value, StyleValue.FromColor); }
    public TextDecoration? TextDecorationLine { init => _style = StyleAccumulator.Add(_style, StyleField.TextDecorationLine, value, StyleValue.FromTextDecoration); }
    public TextSkipInk? TextDecorationSkipInk { init => _style = StyleAccumulator.Add(_style, StyleField.TextDecorationSkipInk, value, StyleValue.FromTextSkipInk); }
    public TextDecorationStyle? TextDecorationStyle { init => _style = StyleAccumulator.Add(_style, StyleField.TextDecorationStyle, value, StyleValue.FromTextDecorationStyle); }
    public Length? TextDecorationThickness { init => _style = StyleAccumulator.Add(_style, StyleField.TextDecorationThickness, value); }
    public FilterMode? TextFilter { init => _style = StyleAccumulator.Add(_style, StyleField.TextFilter, value, StyleValue.FromFilterMode); }
    public Length? TextLineThroughOffset { init => _style = StyleAccumulator.Add(_style, StyleField.TextLineThroughOffset, value); }
    public TextOverflow? TextOverflow { init => _style = StyleAccumulator.Add(_style, StyleField.TextOverflow, value, StyleValue.FromTextOverflow); }
    public Length? TextOverlineOffset { init => _style = StyleAccumulator.Add(_style, StyleField.TextOverlineOffset, value); }
    public Color? TextStrokeColor { init => _style = StyleAccumulator.Add(_style, StyleField.TextStrokeColor, value, StyleValue.FromColor); }
    public Length? TextStrokeWidth { init => _style = StyleAccumulator.Add(_style, StyleField.TextStrokeWidth, value); }
    public TextTransform? TextTransform { init => _style = StyleAccumulator.Add(_style, StyleField.TextTransform, value, StyleValue.FromTextTransform); }
    public Length? TextUnderlineOffset { init => _style = StyleAccumulator.Add(_style, StyleField.TextUnderlineOffset, value); }
    public Goo.PanelTransform? Transform { init => _style = StyleAccumulator.Add(_style, StyleField.Transform, value, StyleValue.FromPanelTransform); }
    public Length? TransformOriginX { init => _style = StyleAccumulator.Add(_style, StyleField.TransformOriginX, value); }
    public Length? TransformOriginY { init => _style = StyleAccumulator.Add(_style, StyleField.TransformOriginY, value); }
    public WhiteSpace? WhiteSpace { init => _style = StyleAccumulator.Add(_style, StyleField.WhiteSpace, value, StyleValue.FromWhiteSpace); }
    public WordBreak? WordBreak { init => _style = StyleAccumulator.Add(_style, StyleField.WordBreak, value, StyleValue.FromWordBreak); }
    public Length? WordSpacing { init => _style = StyleAccumulator.Add(_style, StyleField.WordSpacing, value); }
    public int? ZIndex { init => _style = StyleAccumulator.Add(_style, StyleField.ZIndex, value); }
    public Color? HoverBackgroundColor { init => _style = StyleAccumulator.Add(_style, StyleField.HoverBackgroundColor, value, StyleValue.FromColor); }
    public Color? ActiveBackgroundColor { init => _style = StyleAccumulator.Add(_style, StyleField.ActiveBackgroundColor, value, StyleValue.FromColor); }
    public Color? FocusBackgroundColor { init => _style = StyleAccumulator.Add(_style, StyleField.FocusBackgroundColor, value, StyleValue.FromColor); }
    public Color? HoverFontColor { init => _style = StyleAccumulator.Add(_style, StyleField.HoverFontColor, value, StyleValue.FromColor); }
    public Color? ActiveFontColor { init => _style = StyleAccumulator.Add(_style, StyleField.ActiveFontColor, value, StyleValue.FromColor); }
    public Color? FocusFontColor { init => _style = StyleAccumulator.Add(_style, StyleField.FocusFontColor, value, StyleValue.FromColor); }
    public int? TransitionMs { init => _style = StyleAccumulator.Add(_style, StyleField.TransitionMs, value); }
}
using Goo;
using Sandbox.UI;

namespace Sandbox;

public class CounterUI : GooPanel<Container>
{
	private int _count;

	protected override Container Build() => new Container
	{
		Padding = 16,
		Width = 128,
		Height = 128,
		BackgroundColor = Color.White,
		BorderRadius = 12,
		FlexDirection = FlexDirection.Row,
		Gap = 12,
		AlignItems = Align.Center,
		Children =
		{
			new Text(_count.ToString()),
			new Container
			{
				Padding = 8,
				BackgroundColor = Color.Orange,
				HoverBackgroundColor = Color.Cyan,
				BorderRadius = 6,
				OnClick = e => { _count++; Rebuild(); },
				Children = { new Text("+") },
			},
		},
	};
}
using System;
using System.Collections.Generic;
using Sandbox;

namespace Goo.Input;

// Polls a curated key catalog once per frame for rising-edge presses + modifier state. ReemitHeldOnModifierRise re-emits a held key when a modifier rises (so "hold W, press Ctrl" reads as a chord).
public sealed class KeyTracker
{
    public bool ReemitHeldOnModifierRise { get; set; } = false;

    public ModifierState Modifiers { get; private set; }
    public IReadOnlyList<KeyDescriptor> JustPressed => _justPressed;

    readonly IReadOnlyList<KeyDescriptor> _catalog;
    readonly HashSet<string>     _downLastFrame = new();
    readonly List<KeyDescriptor> _justPressed   = new();

    public KeyTracker() : this( KnownKeys.All ) { }

    public KeyTracker( IReadOnlyList<KeyDescriptor> catalog )
    {
        _catalog = catalog;
    }

    public void Reset()
    {
        _downLastFrame.Clear();
        _justPressed.Clear();
        Modifiers = default;
    }

    static readonly Func<string, bool> s_engineDown = Sandbox.Input.Keyboard.Down;

    public void Poll() => Poll( s_engineDown );

    // isDown seam exists because engine Input statics throw outside a running engine process.
    public void Poll( Func<string, bool> isDown )
    {
        _justPressed.Clear();
        var prev = Modifiers;

        for ( int i = 0; i < _catalog.Count; i++ )
        {
            var  d    = _catalog[i];
            bool down = isDown( d.EngineName );
            if ( down && !_downLastFrame.Contains( d.EngineName ) )
                _justPressed.Add( d );
            if ( down ) _downLastFrame.Add( d.EngineName );
            else        _downLastFrame.Remove( d.EngineName );
        }

        Modifiers = new ModifierState(
            _downLastFrame.Contains( "ctrl"  ),
            _downLastFrame.Contains( "shift" ),
            _downLastFrame.Contains( "alt"   ),
            _downLastFrame.Contains( "win"   ) );

        if ( !ReemitHeldOnModifierRise ) return;

        bool modRose = ( Modifiers.Ctrl  && !prev.Ctrl  ) || ( Modifiers.Shift && !prev.Shift )
                    || ( Modifiers.Alt   && !prev.Alt   ) || ( Modifiers.Meta  && !prev.Meta  );
        if ( !modRose ) return;

        for ( int i = 0; i < _catalog.Count; i++ )
        {
            var d = _catalog[i];
            if ( d.Class == KeyClass.Modifier ) continue;
            if ( !_downLastFrame.Contains( d.EngineName ) ) continue;
            if ( _justPressed.Contains( d ) ) continue;
            _justPressed.Add( d );
        }
    }

    /// <summary>True if the named key had a rising edge (just-pressed, not held) this frame; call Poll first.</summary>
    public bool Pressed( string engineName )
    {
        for ( int i = 0; i < _justPressed.Count; i++ )
            if ( _justPressed[i].EngineName == engineName ) return true;
        return false;
    }
}
using System;
using Sandbox;
using Sandbox.UI;

namespace Goo.Internal;

internal sealed class StatefulLabel : Label, IStatefulHost, IStatefulEventHost
{
    StateController? _state;

    internal Action<MousePanelEvent>? _onClick;
    internal Action<MousePanelEvent>? _onRightClick;
    internal Action<MousePanelEvent>? _onMiddleClick;
    internal Action<MousePanelEvent>? _onMouseEnter;
    internal Action<MousePanelEvent>? _onMouseLeave;
    internal Action<MousePanelEvent>? _onMouseDown;
    internal Action<MousePanelEvent>? _onMouseUp;
    internal Action<MousePanelEvent>? _onMouseMove;
    internal bool    _userSetPointerEvents;
    internal Action? _requestRebuild;
    public Action? RequestRebuild { set => _requestRebuild = value; }

    public void ApplyStateVariants(
        Color? baseBg,  Color? baseFg,
        Color? hoverBg, Color? activeBg, Color? focusBg,
        Color? hoverFg, Color? activeFg, Color? focusFg,
        int? transitionMs)
    {
        _state ??= new StateController(this);
        _state.ApplyVariants(
            baseBg, baseFg,
            hoverBg, activeBg, focusBg,
            hoverFg, activeFg, focusFg,
            transitionMs);
    }

    public void ClearStateVariants() => _state?.ClearVariants();

    public bool HasActiveStateVariants => _state?.HasActiveVariants ?? false;

    public void ApplyEvents(in BlobEvents events)
    {
        _onClick      = events.OnClick;
        _onRightClick = events.OnRightClick;
        _onMiddleClick = events.OnMiddleClick;
        _onMouseEnter = events.OnMouseEnter;
        _onMouseLeave = events.OnMouseLeave;
        _onMouseDown  = events.OnMouseDown;
        _onMouseUp    = events.OnMouseUp;
        _onMouseMove  = events.OnMouseMove;
    }

    public bool HasEventHandlers =>
        _onClick != null || _onRightClick != null || _onMiddleClick != null || _onMouseEnter != null || _onMouseLeave != null ||
        _onMouseDown != null || _onMouseUp != null || _onMouseMove != null;

    public bool UserSetPointerEvents
    {
        get => _userSetPointerEvents;
        set => _userSetPointerEvents = value;
    }

    protected override void OnClick(MousePanelEvent e)
    {
        base.OnClick(e);
        EventDispatch.Fire(_onClick, e, _requestRebuild);
    }

    protected override void OnRightClick(MousePanelEvent e)
    {
        base.OnRightClick(e);
        EventDispatch.Fire(_onRightClick, e, _requestRebuild);
    }

    protected override void OnMiddleClick(MousePanelEvent e)
    {
        base.OnMiddleClick(e);
        EventDispatch.Fire(_onMiddleClick, e, _requestRebuild);
    }

    protected override void OnMouseOver(MousePanelEvent e)
    {
        base.OnMouseOver(e);
        EventDispatch.Fire(_onMouseEnter, e, _requestRebuild);
    }

    protected override void OnMouseOut(MousePanelEvent e)
    {
        base.OnMouseOut(e);
        EventDispatch.Fire(_onMouseLeave, e, _requestRebuild);
    }

    protected override void OnMouseDown(MousePanelEvent e)
    {
        base.OnMouseDown(e);
        EventDispatch.Fire(_onMouseDown, e, _requestRebuild);
    }

    protected override void OnMouseUp(MousePanelEvent e)
    {
        base.OnMouseUp(e);
        EventDispatch.Fire(_onMouseUp, e, _requestRebuild);
    }

    protected override void OnMouseMove(MousePanelEvent e)
    {
        base.OnMouseMove(e);
        EventDispatch.Fire(_onMouseMove, e, _requestRebuild);
    }
}
using System;
using System.Collections.Generic;
using Sandbox;
using Sandbox.Rendering;
using Sandbox.UI;

namespace Goo;

/// <summary>
/// A custom shader applied to a Blob. Point it at a compiled .shader; it parses the shader
/// source's Attribute() declarations to validate uniform names and to reset uniforms other
/// panels have set (panels share one CommandList attribute namespace), and pushes the uniform
/// bag every frame. Set uniforms with the collection initializer (<c>["Name"] = value</c>);
/// a value may be a literal or a per-frame Func. Subclass and override <see cref="Apply"/>
/// only for bespoke per-frame CPU logic.
/// </summary>
public record ShaderEffect
{
    static readonly Dictionary<object, Material> _materialCache = new();
    static readonly Dictionary<object, ShaderSchemaInfo?> _schemaCache = new();

    // Every uniform name any ShaderEffect has pushed this session, with the last value pushed
    // (its runtime type drives the reset conversion). Panels share one CommandList attribute
    // namespace, so a uniform set by one panel persists into every later panel's draw; an
    // effect that does not set a seen uniform must reset it to its shader's declared default
    // or it inherits the other panel's value (view-5u5m). Touched only from Apply (render thread).
    static readonly Dictionary<string, object> _seenUniforms = new();

    internal sealed class ShaderSchemaInfo
    {
        public required HashSet<string> Names;                       // declared attribute names
        public required Dictionary<string, (Vector4 Floats, Vector4 Ints)> Defaults;
    }

    readonly string? _path;
    readonly Shader? _shader;
    readonly GrabMode _grab;
    readonly Dictionary<string, UniformValue> _bag = new();
    bool _validated;

    /// <summary>For subclasses that supply their own <see cref="Material"/> and <see cref="Apply"/>.</summary>
    protected ShaderEffect() { }

    /// <summary>Apply the shader at <paramref name="shaderPath"/> (e.g. "shaders/ui_dither.shader").</summary>
    public ShaderEffect( string shaderPath, GrabMode grab = GrabMode.None )
    {
        _path = shaderPath;
        _grab = grab;
    }

    /// <summary>Apply a shader resource (drag-droppable in the inspector).</summary>
    public ShaderEffect( Shader shader, GrabMode grab = GrabMode.None )
    {
        _shader = shader;
        _grab = grab;
    }

    /// <summary>The shader asset path, or null when constructed from a <see cref="T:Sandbox.Shader"/> resource.</summary>
    public string? ShaderPath => _path;

    /// <summary>How this effect grabs the framebuffer behind its panel.</summary>
    public GrabMode Grab => _grab;

    /// <summary>Get or set a uniform by its shader attribute name.</summary>
    public UniformValue this[string name]
    {
        get => _bag[name];
        set => _bag[name] = value;
    }

    object CacheKey => (object?)_path ?? _shader!;

    /// <summary>The material this effect draws with, cached so it is excluded from record equality.</summary>
    public virtual Material Material
    {
        get
        {
            var key = CacheKey;
            if ( !_materialCache.TryGetValue( key, out var mat ) )
            {
                mat = _path is not null ? Material.FromShader( _path ) : Material.FromShader( _shader! );
                _materialCache[key] = mat;
            }
            return mat;
        }
    }

    /// <summary>Create the Material now, on the calling thread. Call on the main thread; Draw runs on the render thread and must only read the cache.</summary>
    public void Warm() => _ = Material;

    /// <summary>Set this effect's shader attributes for the frame, then grab the framebuffer per <see cref="Grab"/>.</summary>
    protected internal virtual void Apply( CommandList cl, Rect rect )
    {
        cl.Attributes.Set( "BoxSize", new Vector2( rect.Width, rect.Height ) );

        // Subclass escape hatch: a derived effect calling base.Apply gets only BoxSize.
        if ( _path is null && _shader is null ) return;

        Validate();

        // Reset seen-but-unset uniforms to this shader's declared defaults so another panel's
        // attribute writes do not bleed into this draw (view-5u5m).
        var schema = SchemaFor( CacheKey );
        if ( schema is not null )
        {
            foreach ( var (name, sample) in _seenUniforms )
            {
                if ( _bag.ContainsKey( name ) ) continue;
                if ( !schema.Defaults.TryGetValue( name, out var def ) ) continue;
                if ( ResetValue( sample, def.Floats, def.Ints ) is { } reset )
                    SetAttribute( cl, name, reset );
            }
        }

        foreach ( var (name, value) in _bag )
        {
            var resolved = value.Resolve();
            SetAttribute( cl, name, resolved );
            if ( resolved is not Texture )
                _seenUniforms[name] = resolved;
        }

        switch ( _grab )
        {
            case GrabMode.Sharp:
                cl.Attributes.GrabFrameTexture( "FrameBufferCopyTexture" );
                break;
            case GrabMode.Blurred:
                cl.Attributes.GrabFrameTexture( "FrameBufferCopyTexture", Graphics.DownsampleMethod.GaussianBlur );
                break;
        }
    }

    static void SetAttribute( CommandList cl, string name, object value )
    {
        switch ( value )
        {
            case float f:   cl.Attributes.Set( name, f ); break;
            case bool b:    cl.Attributes.Set( name, b ); break;
            case Vector2 v: cl.Attributes.Set( name, v ); break;
            case Vector3 v: cl.Attributes.Set( name, v ); break;
            case Vector4 v: cl.Attributes.Set( name, v ); break;
            case Color c:   cl.Attributes.Set( name, c ); break;
            case Texture t: cl.Attributes.Set( name, t ); break;
        }
    }

    // Reads the shader's declared attribute names once per instance and warns on uniform names
    // the shader does not declare. Skipped silently when the source is unavailable.
    void Validate()
    {
        if ( _validated ) return;
        _validated = true;

        var valid = SchemaFor( CacheKey )?.Names;
        if ( valid is null || valid.Count == 0 ) return;

        foreach ( var name in _bag.Keys )
            if ( !valid.Contains( name ) )
                Sandbox.Internal.GlobalSystemNamespace.Log.Warning(
                    $"ShaderEffect for \"{_path ?? _shader?.ResourcePath}\": uniform \"{name}\" is not declared by the shader " +
                    $"(valid: {string.Join( ", ", valid )}). Ignored." );
    }

    // Names + defaults come from parsing the .shader SOURCE, which ships with the project and
    // declares every Attribute() with its Default(). The engine's Shader.Schema is editor-only
    // plumbing: at game runtime it throws ("Load must be called on the main thread!" — Apply
    // runs on the render thread) so it is not consulted at all (view-5u5m probe, 2026-06-11).
    // Null when the source is unreadable (e.g. unit tests, published build without raw
    // .shader files); reset and validation both skip then.
    static ShaderSchemaInfo? SchemaFor( object key )
    {
        if ( _schemaCache.TryGetValue( key, out var info ) ) return info;

        info = null;
        if ( (key as string ?? (key as Shader)?.ResourcePath) is { } srcPath )
        {
            try
            {
                info = ParseShaderSource( FileSystem.Mounted.ReadAllText( srcPath ) );
            }
            catch
            {
                info = null;
            }
        }

        _schemaCache[key] = info;
        return info;
    }

    static readonly System.Text.RegularExpressions.Regex _declRegex = new(
        @"\b(?<type>float[234]?|bool|int|Texture2D)\s+\w+\s*<(?<block>[^>]*)>",
        System.Text.RegularExpressions.RegexOptions.Compiled );
    static readonly System.Text.RegularExpressions.Regex _attrRegex = new(
        @"Attribute\s*\(\s*""(?<name>[^""]+)""\s*\)",
        System.Text.RegularExpressions.RegexOptions.Compiled );
    static readonly System.Text.RegularExpressions.Regex _defaultRegex = new(
        @"Default[234]?\s*\(\s*(?<args>[^)]*)\)",
        System.Text.RegularExpressions.RegexOptions.Compiled );

    // Pure: extracts Attribute()-bound uniform declarations and their Default() values from
    // .shader source. Defaults are stored in both vector slots so ResetValue can convert by the
    // bled value's runtime type. Texture declarations contribute a name (for validation) but no
    // default. Only the main file is scanned; #include'd uniforms (BoxSize, DpiScale) are
    // framework-managed and excluded anyway. Missing Default() = zeros, matching the engine's
    // unset-attribute behavior.
    internal static ShaderSchemaInfo? ParseShaderSource( string source )
    {
        var names    = new HashSet<string>();
        var defaults = new Dictionary<string, (Vector4 Floats, Vector4 Ints)>();

        foreach ( System.Text.RegularExpressions.Match m in _declRegex.Matches( source ) )
        {
            var block = m.Groups["block"].Value;
            var attr  = _attrRegex.Match( block );
            if ( !attr.Success ) continue;

            var name = attr.Groups["name"].Value;
            names.Add( name );

            if ( name is "BoxSize" or "DpiScale" ) continue;     // framework-managed per draw
            if ( m.Groups["type"].Value == "Texture2D" ) continue; // no resettable default

            Vector4 v = default;
            var def = _defaultRegex.Match( block );
            if ( def.Success )
            {
                var parts = def.Groups["args"].Value.Split( ',' );
                for ( int i = 0; i < parts.Length && i < 4; i++ )
                {
                    if ( !float.TryParse( parts[i].Trim(), System.Globalization.NumberStyles.Float,
                             System.Globalization.CultureInfo.InvariantCulture, out var f ) ) continue;
                    switch ( i )
                    {
                        case 0: v.x = f; break;
                        case 1: v.y = f; break;
                        case 2: v.z = f; break;
                        case 3: v.w = f; break;
                    }
                }
            }
            defaults[name] = (v, v);
        }

        return names.Count > 0 ? new ShaderSchemaInfo { Names = names, Defaults = defaults } : null;
    }

    // Pure: converts a shader's declared default (schema FloatDefault/IntDefault vectors) to the
    // runtime type of the value that bled in, so the reset lands in the same attribute slot type.
    // Null = no safe reset (unsupported type; textures are never recorded so never reach this).
    internal static object? ResetValue( object sample, Vector4 floats, Vector4 ints ) => sample switch
    {
        float   => floats.x,
        bool    => ints.x != 0f,
        Vector2 => new Vector2( floats.x, floats.y ),
        Vector3 => new Vector3( floats.x, floats.y, floats.z ),
        Color   => new Color( floats.x, floats.y, floats.z, floats.w ),
        Vector4 => floats,
        _       => null,
    };

    public virtual bool Equals( ShaderEffect? other )
    {
        if ( other is null ) return false;
        if ( ReferenceEquals( this, other ) ) return true;
        if ( EqualityContract != other.EqualityContract ) return false;
        return _path == other._path
            && ReferenceEquals( _shader, other._shader )
            && _grab == other._grab
            && BagEquals( _bag, other._bag );
    }

    public override int GetHashCode()
    {
        var hc = new HashCode();
        hc.Add( EqualityContract );
        hc.Add( _path );
        hc.Add( _grab );
        hc.Add( _bag.Count );
        return hc.ToHashCode();
    }

    static bool BagEquals( Dictionary<string, UniformValue> a, Dictionary<string, UniformValue> b )
    {
        if ( a.Count != b.Count ) return false;
        foreach ( var (k, v) in a )
            if ( !b.TryGetValue( k, out var bv ) || !v.Equals( bv ) ) return false;
        return true;
    }
}
using System;
using System.Linq;
using Sandbox;

namespace Editor.TerrainConvert;

/// <summary>
/// Which source channel to read the height value from.
/// </summary>
public enum HeightChannel
{
	/// <summary> Red channel only. Standard for grayscale heightmaps. </summary>
	Red,
	Green,
	Blue,
	Alpha,
	/// <summary> Rec.709 weighted luminance of RGB. </summary>
	Luminance,
	/// <summary> Average of the RGB channels. </summary>
	Average,
	/// <summary> The largest of the RGB channels. </summary>
	Max,
}

/// <summary>
/// Bit depth of the output .raw file. s&box terrain stores heights as 16-bit,
/// so 16-bit is recommended for the best precision.
/// </summary>
public enum HeightBitDepth
{
	/// <summary> 16-bit per height sample (recommended). 2 bytes per pixel. </summary>
	Bit16,
	/// <summary> 8-bit per height sample. 1 byte per pixel. </summary>
	Bit8,
}

/// <summary>
/// How the source values are remapped into the 0..1 height range before quantizing.
/// </summary>
public enum HeightNormalize
{
	/// <summary> Use values as-is, clamped to 0..1. </summary>
	Clamp,
	/// <summary> Stretch the min..max range of the image to fill 0..1 (good for HDR/EXR). </summary>
	MinMaxStretch,
}

/// <summary>
/// Byte order of multi-byte (16-bit) samples in the output file.
/// </summary>
public enum HeightByteOrder
{
	/// <summary> Little-endian. What the s&box terrain importer reads by default ("Windows"). </summary>
	LittleEndian,
	/// <summary> Big-endian ("Mac"). </summary>
	BigEndian,
}

/// <summary>
/// Settings for converting an image into a terrain heightmap .raw file.
/// </summary>
public class HeightmapConvertSettings
{
	/// <summary>
	/// Which channel of the source image holds the height. Most heightmaps are
	/// grayscale, where every channel is identical - <see cref="HeightChannel.Red"/> works for those.
	/// </summary>
	[Property]
	public HeightChannel Channel { get; set; } = HeightChannel.Red;

	/// <summary>
	/// 16-bit gives the smoothest terrain and matches what s&box stores internally.
	/// </summary>
	[Property]
	public HeightBitDepth BitDepth { get; set; } = HeightBitDepth.Bit16;

	/// <summary>
	/// Output heightmaps are always square. If 0, the smaller of the source
	/// dimensions is used. The image is resampled to this resolution.
	/// </summary>
	[Property, Range( 0, 8192 )]
	public int Resolution { get; set; } = 0;

	/// <summary>
	/// Round the output resolution down to the nearest power of two (e.g 1024, 2048).
	/// The terrain system expects power-of-two heightmaps, so leave this on.
	/// </summary>
	[Property]
	public bool PowerOfTwo { get; set; } = true;

	/// <summary>
	/// How source values are mapped to the height range. Use <see cref="HeightNormalize.MinMaxStretch"/>
	/// for HDR images that don't already fill 0..1.
	/// </summary>
	[Property]
	public HeightNormalize Normalize { get; set; } = HeightNormalize.Clamp;

	/// <summary>
	/// Flip the image vertically. Image and terrain coordinate origins often differ;
	/// toggle this if your terrain comes out mirrored north/south.
	/// </summary>
	[Property]
	public bool FlipVertical { get; set; } = false;

	/// <summary>
	/// Invert the heights (high becomes low). Useful for depth/inverted maps.
	/// </summary>
	[Property]
	public bool Invert { get; set; } = false;

	/// <summary>
	/// Byte order of 16-bit samples. The s&box importer reads little-endian by default.
	/// </summary>
	[Property, ShowIf( nameof( BitDepth ), HeightBitDepth.Bit16 )]
	public HeightByteOrder ByteOrder { get; set; } = HeightByteOrder.LittleEndian;
}

/// <summary>
/// Converts loaded images into raw single-channel heightmaps compatible with the
/// s&box terrain importer (square, 8 or 16 bit, raw samples with no header).
/// </summary>
public static class HeightmapConverter
{
	/// <summary>
	/// Convert a bitmap into a raw heightmap byte buffer.
	/// </summary>
	/// <param name="bitmap">Source image.</param>
	/// <param name="settings">Conversion settings.</param>
	/// <param name="resolution">The square resolution of the produced heightmap.</param>
	/// <returns>Raw heightmap bytes ready to write to a .raw file.</returns>
	public static byte[] Convert( Bitmap bitmap, HeightmapConvertSettings settings, out int resolution )
	{
		ArgumentNullException.ThrowIfNull( bitmap );
		ArgumentNullException.ThrowIfNull( settings );

		var pixels = bitmap.GetPixels();
		int count = bitmap.Width * bitmap.Height;

		// Extract the chosen channel as a float per pixel, then run the shared pipeline.
		var values = new float[count];
		for ( int i = 0; i < count; i++ )
			values[i] = SampleChannel( pixels[i], settings.Channel );

		return BuildRaw( values, bitmap.Width, bitmap.Height, settings, out resolution );
	}

	/// <summary>
	/// Convert a decoded EXR into a raw heightmap byte buffer, reading height from the
	/// chosen channel (falling back to Y/R/first channel if the exact one is absent).
	/// </summary>
	public static byte[] Convert( ExrImage exr, HeightmapConvertSettings settings, out int resolution )
	{
		ArgumentNullException.ThrowIfNull( exr );
		ArgumentNullException.ThrowIfNull( settings );

		var values = SampleChannel( exr, settings.Channel );
		return BuildRaw( values, exr.Width, exr.Height, settings, out resolution );
	}

	/// <summary>
	/// Shared pipeline: resample a single-channel float plane to a square power-of-two,
	/// normalize into 0..1, optionally invert, and quantize to raw bytes.
	/// </summary>
	static byte[] BuildRaw( float[] values, int srcWidth, int srcHeight, HeightmapConvertSettings settings, out int resolution )
	{
		resolution = ResolveResolution( srcWidth, srcHeight, settings );

		// Bilinear resample to a square of the target resolution, working entirely in float
		// so we don't lose precision on high bit-depth / HDR sources. Resampling produces a
		// fresh array; otherwise clone so the in-place normalize/invert never mutates a
		// caller-owned buffer (e.g. an EXR's cached channel plane).
		values = srcWidth != resolution || srcHeight != resolution
			? ResampleBilinear( values, srcWidth, srcHeight, resolution, resolution )
			: (float[])values.Clone();

		ApplyNormalize( values, settings.Normalize );

		if ( settings.Invert )
		{
			for ( int i = 0; i < values.Length; i++ )
				values[i] = 1f - values[i];
		}

		return Quantize( values, resolution, settings );
	}

	static float[] ResampleBilinear( float[] src, int srcW, int srcH, int dstW, int dstH )
	{
		var dst = new float[dstW * dstH];

		for ( int y = 0; y < dstH; y++ )
		{
			float fy = dstH > 1 ? (float)y / (dstH - 1) * (srcH - 1) : 0f;
			int y0 = (int)fy;
			int y1 = Math.Min( y0 + 1, srcH - 1 );
			float ty = fy - y0;

			for ( int x = 0; x < dstW; x++ )
			{
				float fx = dstW > 1 ? (float)x / (dstW - 1) * (srcW - 1) : 0f;
				int x0 = (int)fx;
				int x1 = Math.Min( x0 + 1, srcW - 1 );
				float tx = fx - x0;

				float top = MathX.Lerp( src[y0 * srcW + x0], src[y0 * srcW + x1], tx );
				float bottom = MathX.Lerp( src[y1 * srcW + x0], src[y1 * srcW + x1], tx );
				dst[y * dstW + x] = MathX.Lerp( top, bottom, ty );
			}
		}

		return dst;
	}

	static float[] SampleChannel( ExrImage exr, HeightChannel channel )
	{
		// For multi-channel EXRs, blend RGB the same way the bitmap path does. For the
		// common single-channel (Y) heightmap, every option resolves to that one plane.
		switch ( channel )
		{
			case HeightChannel.Red: return exr.GetHeightChannel( "R" );
			case HeightChannel.Green: return exr.GetHeightChannel( "G" );
			case HeightChannel.Blue: return exr.GetHeightChannel( "B" );
			case HeightChannel.Alpha: return exr.GetHeightChannel( "A" );
		}

		var r = exr.GetChannel( "R" );
		var g = exr.GetChannel( "G" );
		var b = exr.GetChannel( "B" );

		// No RGB set - it's a luminance/single-channel image, use it directly.
		if ( r is null || g is null || b is null )
			return exr.GetHeightChannel();

		var outv = new float[r.Length];
		for ( int i = 0; i < outv.Length; i++ )
		{
			outv[i] = channel switch
			{
				HeightChannel.Luminance => 0.2126f * r[i] + 0.7152f * g[i] + 0.0722f * b[i],
				HeightChannel.Average => (r[i] + g[i] + b[i]) / 3f,
				HeightChannel.Max => Math.Max( r[i], Math.Max( g[i], b[i] ) ),
				_ => r[i],
			};
		}
		return outv;
	}

	static int ResolveResolution( int width, int height, HeightmapConvertSettings settings )
	{
		int res = settings.Resolution > 0 ? settings.Resolution : Math.Min( width, height );

		if ( settings.PowerOfTwo )
			res = RoundDownToPowerOfTwo( res );

		return Math.Clamp( res, 4, 16384 );
	}

	static float SampleChannel( Color c, HeightChannel channel ) => channel switch
	{
		HeightChannel.Red => c.r,
		HeightChannel.Green => c.g,
		HeightChannel.Blue => c.b,
		HeightChannel.Alpha => c.a,
		HeightChannel.Luminance => 0.2126f * c.r + 0.7152f * c.g + 0.0722f * c.b,
		HeightChannel.Average => (c.r + c.g + c.b) / 3f,
		HeightChannel.Max => Math.Max( c.r, Math.Max( c.g, c.b ) ),
		_ => c.r,
	};

	static void ApplyNormalize( float[] values, HeightNormalize mode )
	{
		if ( mode == HeightNormalize.MinMaxStretch )
		{
			float min = values.Min();
			float max = values.Max();
			float range = max - min;

			if ( range > 1e-6f )
			{
				for ( int i = 0; i < values.Length; i++ )
					values[i] = (values[i] - min) / range;
				return;
			}
			// Flat image - fall through to clamp.
		}

		for ( int i = 0; i < values.Length; i++ )
			values[i] = Math.Clamp( values[i], 0f, 1f );
	}

	static byte[] Quantize( float[] values, int resolution, HeightmapConvertSettings settings )
	{
		bool flip = settings.FlipVertical;

		if ( settings.BitDepth == HeightBitDepth.Bit8 )
		{
			var bytes = new byte[resolution * resolution];
			for ( int y = 0; y < resolution; y++ )
			{
				int srcY = flip ? resolution - 1 - y : y;
				for ( int x = 0; x < resolution; x++ )
				{
					float v = Math.Clamp( values[srcY * resolution + x], 0f, 1f );
					bytes[y * resolution + x] = (byte)MathF.Round( v * byte.MaxValue );
				}
			}
			return bytes;
		}
		else
		{
			bool little = settings.ByteOrder == HeightByteOrder.LittleEndian;
			var bytes = new byte[resolution * resolution * 2];
			for ( int y = 0; y < resolution; y++ )
			{
				int srcY = flip ? resolution - 1 - y : y;
				for ( int x = 0; x < resolution; x++ )
				{
					float v = Math.Clamp( values[srcY * resolution + x], 0f, 1f );
					ushort h = (ushort)MathF.Round( v * ushort.MaxValue );

					int o = (y * resolution + x) * 2;
					if ( little )
					{
						bytes[o] = (byte)(h & 0xFF);
						bytes[o + 1] = (byte)(h >> 8);
					}
					else
					{
						bytes[o] = (byte)(h >> 8);
						bytes[o + 1] = (byte)(h & 0xFF);
					}
				}
			}
			return bytes;
		}
	}

	/// <summary>
	/// Rounds a value down to the nearest power of two.
	/// </summary>
	public static int RoundDownToPowerOfTwo( int value )
	{
		if ( value < 1 ) return 1;
		value |= value >> 1;
		value |= value >> 2;
		value |= value >> 4;
		value |= value >> 8;
		value |= value >> 16;
		return value - (value >> 1);
	}
}
using Sandbox.Citizen;

namespace ShrimpleCharacterController;

[Hide]
public sealed class ShrimpleFlyer : Component
{
    [RequireComponent]
    public ShrimpleCharacterController Controller { get; set; }
    public GameObject Camera { get; set; }

    [Property]
    [Range(400f, 1600f)]
    public float WalkSpeed { get; set; } = 800f;

    [Property]
    [Range(800f, 4000f)]
    public float RunSpeed { get; set; } = 2400f;

    public Angles EyeAngles { get; set; }

    protected override void OnStart()
    {
        base.OnStart();

        Camera = new GameObject(true, "Camera");
        Camera.SetParent(GameObject);
        var cameraComponent = Camera.Components.Create<CameraComponent>();
        cameraComponent.ZFar = 32768f;
    }

    protected override void OnFixedUpdate()
    {
        base.OnFixedUpdate();

        var isDucking = Input.Down("Duck");
        var isRunning = Input.Down("Run");
        var ascending = Input.Down("Jump") ? 1f : 0f;
        var descending = Input.Down("Duck") ? -1f : 0f;
        var wishSpeed = isRunning ? RunSpeed : WalkSpeed;
        var wishDirection = (Input.AnalogMove + Vector3.Up * (ascending + descending)).Normal * EyeAngles.ToRotation();

        Controller.WishVelocity = wishDirection * wishSpeed;
        Controller.Move();
    }

    protected override void OnUpdate()
    {
        base.OnUpdate();

        EyeAngles += Input.AnalogLook;
        EyeAngles = EyeAngles.WithPitch(MathX.Clamp(EyeAngles.pitch, -40f, 40f));

        var cameraOffset = Vector3.Up * 70f + Vector3.Backward * 760f;
        Camera.WorldRotation = EyeAngles.ToRotation();
        Camera.LocalPosition = cameraOffset * Camera.WorldRotation;
    }
}
#if DEBUG

using Sandbox.Reactivity.Internals;
using Sandbox.UI;

namespace Sandbox.Reactivity.Editor.Debugger;

// ReSharper disable once ClassNeverInstantiated.Global
[Dock("Editor", "Reactivity Debugger", "local_fire_department")]
internal sealed partial class DebuggerWidget : Widget
{
	private readonly TreeView _tree;

	public DebuggerWidget(Widget? parent)
		: base(parent)
	{
		Layout = new Column
		{
			Spacing = 2,
			Children =
			[
				new Widget
				{
					Layout = new Row
					{
						Spacing = 2,
						Children =
						[
							// TODO: search bar
							new Widget
							{
								HorizontalSizeMode = SizeMode.Flexible,
							},
							new Widget
							{
								BackgroundColor = Theme.ControlBackground,
								BorderRadius = Theme.ControlRadius,
								Layout = new Row
								{
									Children =
									[
										new ToolButton("Settings", "more_vert", this)
										{
											MouseLeftPress = () => Settings<DebuggerWidget>.OpenContextMenu(this),
										},
									],
								},
							},
						],
					},
				},
				new Widget
				{
					BackgroundColor = Theme.ControlBackground,
					BorderRadius = Theme.ControlRadius,
					Layout = new Column
					{
						Children =
						[
							_tree = new TreeView
							{
								Margin = new Margin(8, 0),
								SelectionOverride = () => EditorUtility.InspectorObject,
							},
						],
					},
				},
			],
		};

		Effect.OnEffectRootCreated += OnEffectRootCreated;
	}

	public override void OnDestroyed()
	{
		foreach (var item in _tree.Items) // .Items makes a copy
		{
			if (item is EffectTreeNode node)
			{
				node.Dispose();
			}
		}

		_tree.Clear();

		Effect.OnEffectRootCreated -= OnEffectRootCreated;
	}

	private void OnEffectRootCreated(Effect root)
	{
		if (root.IsDisposed)
		{
			// just in case - effects from other scenes (e.g. prefab editors) might cause this to happen
			return;
		}

		if (!ShowUiEffects && root.Parent is IReactivePanel)
		{
			return;
		}

		if (!ShowGameplayEffects && root.Parent is (Component or GameObject) and not IReactivePanel)
		{
			return;
		}

		var node = new EffectTreeNode(root);
		_tree.AddItem(node);

		if (AutoExpand)
		{
			_tree.Open(node, true);
		}
	}
}

#endif
#if DEBUG

using Sandbox.Reactivity.Internals;

namespace Sandbox.Reactivity.Editor.Inspector;

internal class SerializedReactiveObjectProperty(IReactiveObject reactive) : SerializedProperty
{
	protected readonly IReactiveObject ReactiveObject = reactive;

	public override string Name { get; } = reactive.Name ?? "Reactive Object";

	public override string DisplayName => Name;

	public override Type PropertyType => ReactiveObject.GetType();

	public override bool IsEditable => false;

	public override bool IsValid => ReactiveObject is not Effect { IsDisposed: true } && base.IsValid;

	public override void SetValue<T>(T value)
	{
	}

	public override T GetValue<T>(T defaultValue = default!)
	{
		return ValueToType(ReactiveObject, defaultValue);
	}
}

#endif
global using static Sandbox.Internal.GlobalGameNamespace;
global using Microsoft.AspNetCore.Components;
global using Microsoft.AspNetCore.Components.Rendering;
[assembly: global::System.Reflection.AssemblyMetadata( "AddonTitle", "Reactivity" )]
[assembly: global::System.Reflection.AssemblyMetadata( "AddonIdent", "reactivity" )]
[assembly: global::System.Reflection.AssemblyMetadata( "OrgIdent", "igor" )]
[assembly: global::System.Reflection.AssemblyMetadata( "Ident", "igor.reactivity" )]
[assembly: global::System.Reflection.AssemblyMetadata( "EngineVersion", "26" )]
[assembly: global::System.Reflection.AssemblyMetadata( "EngineMinorVersion", "1" )]

[assembly: System.Runtime.Versioning.TargetFramework( ".NETCoreApp,Version=v9.0", FrameworkDisplayName = ".NET 9.0" )]
[assembly: global::System.Reflection.AssemblyMetadata( "CompileTime", "2026-06-27T21:09:21.7423840Z" )]
[assembly: global::System.Reflection.AssemblyVersion("0.0.111.0")]
[assembly: global::System.Reflection.AssemblyFileVersion("0.0.111.0")]
using System.Runtime.CompilerServices;

namespace Sandbox.Reactivity.Internals.Runtimes;

internal sealed class Runtime : IDisposable
{
	/// <summary>
	/// Effects that are waiting to run due to reactivity changes.
	/// </summary>
	private readonly Queue<Effect> _pendingEffects = new(16);

	/// <summary>
	/// How many effects have run during a flush operation.
	/// </summary>
	private uint _flushDepth;

	/// <summary>
	/// Whether pending effects are currently being run.
	/// </summary>
	private bool _isFlushing;

	/// <summary>
	/// The currently executing effect.
	/// </summary>
	public Effect? CurrentEffect { get; set; }

	/// <summary>
	/// The currently executing reaction.
	/// </summary>
	public IReaction? CurrentReaction { get; set; }

	/// <summary>
	/// A monotonically increasing counter that's incremented when an <see cref="IProducer" /> updates its current
	/// value.
	/// </summary>
	public uint Version { get; set; } = 1;

	/// <summary>
	/// Whether dependency tracking is currently disabled.
	/// </summary>
	public bool IsUntracking { get; set; }

	/// <summary>
	/// Whether a flush was scheduled to run at the end of the frame.
	/// </summary>
	public bool IsFlushScheduled { get; private set; }

	/// <summary>
	/// Whether an effect is currently executing its teardown function. This is used by producers to skip any
	/// recomputation when accessed to ensure the previous value is returned.
	/// </summary>
	public bool IsRunningTeardown { get; set; }

	public void Dispose()
	{
		_pendingEffects.Clear();
		CurrentEffect = null;
		CurrentReaction = null;
		Version = uint.MaxValue;
		IsUntracking = true;
		IsFlushScheduled = false;
		_isFlushing = false;
	}

	/// <summary>
	/// Returns the currently executing effect.
	/// </summary>
	/// <exception cref="InvalidOperationException">
	/// Thrown if there is no effect that is currently executing.
	/// </exception>
	public Effect EnsureCurrentEffect([CallerMemberName] string name = "Effect")
	{
		return CurrentEffect ?? throw new InvalidOperationException(name + " must be created in an effect root");
	}

	public void ScheduleEffect(Effect effect)
	{
		_pendingEffects.Enqueue(effect);

		if (!IsFlushScheduled && !_isFlushing)
		{
			IsFlushScheduled = true;
		}
	}

	/// <summary>
	/// Empties the queue of effects that are scheduled to run due to one of their dependencies changing. This should
	/// only be run when you want an effect to re-run immediately after changing a reactive value.
	/// </summary>
	public void Flush()
	{
		if (_isFlushing)
		{
			return;
		}

		_isFlushing = true;
		IsFlushScheduled = false;

		try
		{
			while (_pendingEffects.TryDequeue(out var effect))
			{
				if (_flushDepth++ > 1000)
				{
					_pendingEffects.Clear();
					_pendingEffects.TrimExcess(16);

#if DEBUG
					var exception = new InfiniteLoopException(_effectExecutions);
					OnFlushInfiniteLoop?.Invoke(exception);

					throw exception;
#else
					throw new InfiniteLoopException();
#endif
				}

				if (effect.ShouldRun)
				{
					effect.Run();
#if DEBUG
					_effectExecutions[effect] = _effectExecutions.GetValueOrDefault(effect) + 1;
#endif
				}
			}
		}
		finally
		{
			_flushDepth = 0;
			_isFlushing = false;
#if DEBUG
			_effectExecutions.Clear();
#endif
		}
	}

#if DEBUG
	/// <summary>
	/// Which effects have executing during the current flush, and how many times they've executed.
	/// </summary>
	private readonly Dictionary<Effect, int> _effectExecutions = [];

	/// <summary>
	/// Called when an infinite loop occurred during a flush.
	/// </summary>
	public static event Action<InfiniteLoopException>? OnFlushInfiniteLoop;
#endif
}
#if SANDBOX
using System.Diagnostics;
using Sandbox.Reactivity.Internals;
using Sandbox.UI;
using static Sandbox.Reactivity.Reactive;
#if JETBRAINS_ANNOTATIONS
using JetBrains.Annotations;
#endif

namespace Sandbox.Reactivity;

/// <summary>
/// The reactive counterpart to <see cref="Panel" /> that allows usage of reactive properties.
/// </summary>
/// <remarks>
/// Make sure you set up an effect root using <see cref="PanelRoot" /> at the top of your razor markup:
/// <code>
/// @{ using var _ = PanelRoot(); }
/// </code>
/// Engine limitations prevent this from being done automatically.
/// </remarks>
#if JETBRAINS_ANNOTATIONS
[PublicAPI]
#endif
public class ReactivePanel : Panel, IReactivePropertyContainer, IReactivePanel
{
	private Effect? _effectRoot;

	private Effect? _renderEffectRoot;

	private int _version;

	public ReactivePanel()
	{
		var parent = Runtime.CurrentEffect;

		_effectRoot = new Effect([StackTraceHidden] [DebuggerStepThrough]() =>
			{
				OnActivate();
				return null;
			},
			parent,
			false);

		_effectRoot.SetDebugInfo(DisplayInfo.For(this).Name,
			DisplayInfo.For(this).Icon,
			new CallLocation(GetType(), nameof(OnActivate)),
			parent ?? (object?)this);

		_effectRoot.Run();
	}

	Effect? IReactivePanel.RenderEffectRoot
	{
		get => _renderEffectRoot;
		set => _renderEffectRoot = value;
	}

	int IReactivePanel.Version
	{
		get => _version;
		set => _version = value;
	}

	Dictionary<int, IProducer> IReactivePropertyContainer.Producers { get; } = [];

	protected ReactivePanelScope PanelRoot()
	{
		return new ReactivePanelScope(this);
	}

	public sealed override void Delete(bool immediate = false)
	{
		_renderEffectRoot?.Dispose();
		_renderEffectRoot = null;

		_effectRoot?.Dispose();
		_effectRoot = null;

		base.Delete(immediate);
	}

	protected sealed override int BuildHash()
	{
		return _version;
	}

	/// <summary>
	/// Called inside an effect root when this panel is instantiated, allowing for effects to be created. When this
	/// panel is deleted, the effect root (and all of its descendants) are disposed.
	/// </summary>
	protected virtual void OnActivate()
	{
	}
}
#endif
#if SANDBOX
using Sandbox.Reactivity.Internals;
#if JETBRAINS_ANNOTATIONS
using JetBrains.Annotations;
#endif

// we can't wrap the BuildRenderTree method for razor components, so we need something that can set up the proper
// scope inside the markup itself

namespace Sandbox.Reactivity;

/// <summary>
/// A disposable that's used to enable reactivity for a <see cref="ReactivePanelComponent" /> or
/// <see cref="ReactivePanel" /> during rendering.
/// </summary>
#if JETBRAINS_ANNOTATIONS
[PublicAPI]
#endif
public readonly ref struct ReactivePanelScope : IDisposable
{
	private readonly Effect.ExecutionScope _executionScope;

	internal ReactivePanelScope(IReactivePanel panel)
	{
		if (panel.RenderEffectRoot is { } previousRoot)
		{
			// don't teardown previous root since we're already building the render tree by this point
			previousRoot.Dispose(false);
		}

		// nested panels don't render immediately when a containing panel's tree is rendering, so the parent is
		// always null anyway
		var effectRoot = new Effect(null, null, true, () => panel.Version++);
		effectRoot.SetDebugInfo(panel.GetType().ToSimpleString(false) + " (Render)",
			panel is ReactivePanel ? "view_quilt" : "monitor",
			new CallLocation(2),
			panel is ReactivePanel reactive ? reactive.GameObject?.GetComponent<IReactivePanel>() : panel);

		panel.RenderEffectRoot = effectRoot;
		_executionScope = new Effect.ExecutionScope(effectRoot);
	}

	public void Dispose()
	{
		_executionScope.Dispose();
	}
}
#endif
#if SANDBOX
namespace Sandbox.Reactivity.Internals;

/// <summary>
/// Maintains a list of types that are assignable to the given type.
/// </summary>
internal static class TypeHierarchy<T>
{
	/// <summary>
	/// All types that are assignable to <typeparamref name="T"/>.
	/// </summary>
	[SkipHotload]
	// ReSharper disable once StaticMemberInGenericType
	public static readonly IEnumerable<Type> Types;

	static TypeHierarchy()
	{
		// since this is most likely going to be used for simple event types, we're going to assume that the hierarchy
		// won't be very large and that checking a list would be faster than hashing for a set
		var next = typeof(T);
		var hierarchy = new List<Type>();

		while (next != null)
		{
			hierarchy.Add(next);

			foreach (var type in next.GetInterfaces())
			{
				if (!hierarchy.Contains(type))
				{
					hierarchy.Add(type);
				}
			}

			next = next.BaseType;

			if (next == typeof(object))
			{
				break;
			}
		}

		Types = hierarchy;
	}
}
#endif
#if JETBRAINS_ANNOTATIONS
#endif

namespace Sandbox.Reactivity;

/// <summary>
/// An object that contains a reactive value. Reading the value inside an effect will cause it to re-run when it
/// changes.
/// </summary>
/// <typeparam name="T">The type of value this object contains.</typeparam>
/// <remarks>
/// This can be used to abstract over a <see cref="State{T}" /> or <see cref="Derived{T}" /> as needed.
/// </remarks>
#if JETBRAINS_ANNOTATIONS
#endif
public interface IState<T>
{
	/// <summary>
	/// The current value.
	/// </summary>
	T Value { get; set; }
}

/// <inheritdoc cref="IState{T}" />
#if JETBRAINS_ANNOTATIONS
#endif
public interface IReadOnlyState<out T>
{
	/// <inheritdoc cref="IState{T}.Value" />
	T Value { get; }
}
using System.Text.Json.Serialization;

namespace Grains.RazorDesigner.Document;

public sealed record CheckboxPayload : Payload
{
    [JsonIgnore]
    public override ControlType Kind => ControlType.Checkbox;

    // Checkbox label text. Overrides Payload.Content (neutral default "").
    public override string Content { get; init; } = "";

    public override Length CheckboxSize { get; init; } = Length.Px( 16 );
}
using Editor;
using Grains.RazorDesigner.Document;
using Sandbox;

namespace Grains.RazorDesigner.Inspector;

[CustomEditor( typeof( Edges ) )]
public sealed class EdgesControlWidget : ControlWidget
{
	private const string LogPrefix = "[Grains.RazorDesigner]";

	public override bool SupportsMultiEdit => true;

	private readonly EdgesProxy _proxy;
	private readonly SerializedObject _proxySerialized;
	// Synchronous change events on both sides; without this guard SetValue would loop.
	private bool _syncing;

	private sealed class EdgesProxy
	{
		public Length Top    { get; set; } = Length.Px( 0 );
		public Length Right  { get; set; } = Length.Px( 0 );
		public Length Bottom { get; set; } = Length.Px( 0 );
		public Length Left   { get; set; } = Length.Px( 0 );
	}

	public EdgesControlWidget( SerializedProperty property ) : base( property )
	{
		Log.Info( $"{LogPrefix} EdgesControlWidget ctor for {property.Name}" );

		Layout = Layout.Column();
		Layout.Spacing = 2;

		_proxy = new EdgesProxy();
		_proxySerialized = EditorTypeLibrary.GetSerializedObject( _proxy );

		var topRow = Layout.Add( Layout.Row() );
		topRow.Spacing = 2;
		AddSide( topRow, nameof( EdgesProxy.Top    ), "border_top"    );
		AddSide( topRow, nameof( EdgesProxy.Right  ), "border_right"  );

		var bottomRow = Layout.Add( Layout.Row() );
		bottomRow.Spacing = 2;
		AddSide( bottomRow, nameof( EdgesProxy.Bottom ), "border_bottom" );
		AddSide( bottomRow, nameof( EdgesProxy.Left   ), "border_left"   );

		_proxySerialized.OnPropertyChanged += OnProxyChanged;

		SyncFromProperty();
	}

	private void AddSide( Layout row, string propName, string icon )
	{
		var prop = _proxySerialized.GetProperty( propName );
		var lengthWidget = new LengthControlWidget( prop, icon );
		row.Add( lengthWidget, 1 );
	}

	protected override void PaintControl()
	{
		// nothing
	}

	private void SyncFromProperty()
	{
		if ( _syncing ) return;
		_syncing = true;

		try
		{
			var e = SerializedProperty.GetValue<Edges>( Edges.Zero );

			_proxySerialized.GetProperty( nameof( EdgesProxy.Top    ) ).SetValue( e.Top );
			_proxySerialized.GetProperty( nameof( EdgesProxy.Right  ) ).SetValue( e.Right );
			_proxySerialized.GetProperty( nameof( EdgesProxy.Bottom ) ).SetValue( e.Bottom );
			_proxySerialized.GetProperty( nameof( EdgesProxy.Left   ) ).SetValue( e.Left );
		}
		finally
		{
			_syncing = false;
		}
	}

	private void OnProxyChanged( SerializedProperty property )
	{
		if ( _syncing ) return;
		if ( ReadOnly || !SerializedProperty.IsEditable )
			return;

		_syncing = true;
		try
		{
			var newValue = new Edges( _proxy.Top, _proxy.Right, _proxy.Bottom, _proxy.Left );

			Log.Info( $"{LogPrefix} EdgesControlWidget OnProxyChanged {newValue}" );

			PropertyStartEdit();
			SerializedProperty.SetValue( newValue );
			SignalValuesChanged();
			PropertyFinishEdit();
		}
		finally
		{
			_syncing = false;
		}
	}

	protected override void OnValueChanged()
	{
		base.OnValueChanged();
		SyncFromProperty();
	}
}
using System;
using System.Collections.Generic;
using Editor;
using Grains.RazorDesigner.Common;
using Grains.RazorDesigner.Contracts;
using Grains.RazorDesigner.Document;
using Grains.RazorDesigner.Templates;
using Sandbox;

namespace Grains.RazorDesigner.Palette;

public class PalettePanel : Widget
{
	private const string LogPrefix = "[Grains.RazorDesigner]";
	private const string CookiePrefix = "razordesigner.palette.";

	// Click-to-add target. Window decides where the new record goes (typically active selection or root).
	public event Action<ControlType> TypeAddRequested;

	// Click-to-add a saved template. Window decides where to insert.
	public event Action<PaletteTemplate> TemplateAddRequested;

	private readonly PaletteTemplateStore _templateStore = new();
	private CollapsibleSection _templatesSection;
	private WrapPanel _templatesWrap;
	public PaletteTemplateStore TemplateStore => _templateStore;

	public PalettePanel( Widget parent ) : base( parent )
	{
		Layout = Layout.Column();
		Layout.Margin = 0;
		Layout.Spacing = 0;
		MinimumWidth = 180;
		VerticalSizeMode = SizeMode.CanGrow;

		var byCategory = new Dictionary<ControlCategory, List<ControlType>>();
		foreach ( ControlType type in Enum.GetValues( typeof( ControlType ) ) )
		{
			var cat = ControlDefaults.For( type ).Category;
			if ( !byCategory.TryGetValue( cat, out var list ) )
			{
				list = new List<ControlType>();
				byCategory[cat] = list;
			}
			list.Add( type );
		}

		// Templates section (top of palette). Hidden when store is empty; rebuilt on Changed.
		_templatesSection = new CollapsibleSection( this, "Templates", "bookmark" );
		_templatesWrap = new WrapPanel( null )
		{
			MinItemWidth = 92,
			ItemHeight = (int)( Theme.RowHeight + 4 ),
			HSpacing = 4,
			VSpacing = 4,
			PaddingLeft = 4,
			PaddingTop = 4,
			PaddingRight = 14,
			PaddingBottom = 4,
		};
		_templatesSection.BodyLayout.Add( _templatesWrap );

		var templatesCookie = $"{CookiePrefix}templates.expanded";
		_templatesSection.Expanded = EditorCookie.Get<bool>( templatesCookie, true );
		_templatesSection.ExpandedChanged += expanded =>
		{
			EditorCookie.Set( templatesCookie, expanded );
			Log.Info( $"{LogPrefix} Palette Templates {(expanded ? "expanded" : "collapsed")}" );
		};

		Layout.Add( _templatesSection );

		_templateStore.Changed += RebuildTemplatesSection;
		_templateStore.Scan(); // initial fill (also fires Changed and rebuilds the section)

		foreach ( ControlCategory cat in Enum.GetValues( typeof( ControlCategory ) ) )
		{
			if ( !byCategory.TryGetValue( cat, out var list ) ) continue;

			var section = new CollapsibleSection(
				this,
				ControlDefaults.CategoryDisplayName( cat ),
				CategoryIcon( cat ) );

			var wrap = new WrapPanel( null )
			{
				MinItemWidth = 92,
				ItemHeight = (int)( Theme.RowHeight + 4 ),
				HSpacing = 4,
				VSpacing = 4,
				PaddingLeft = 4,
				PaddingTop = 4,
				PaddingRight = 14,    // clear the ScrollArea's vertical scrollbar
				PaddingBottom = 4,
			};
			section.BodyLayout.Add( wrap );

			foreach ( var t in list )
				new PaletteTypeButton( wrap, this, t );

			var cookieKey = $"{CookiePrefix}{cat}.expanded";
			section.Expanded = EditorCookie.Get<bool>( cookieKey, DefaultExpanded( cat ) );
			section.ExpandedChanged += expanded =>
			{
				EditorCookie.Set( cookieKey, expanded );
				Log.Info( $"{LogPrefix} Palette category {cat} {(expanded ? "expanded" : "collapsed")}" );
			};

			Layout.Add( section );
		}

		Layout.AddStretchCell();

		Log.Info( $"{LogPrefix} PalettePanel ctor (icon grid, {byCategory.Count} categories)" );
	}

	internal void NotifyTypeClicked( ControlType type )
	{
		Log.Info( $"{LogPrefix} PalettePanel.NotifyTypeClicked: {type}" );
		TypeAddRequested?.Invoke( type );
	}

	internal void NotifyTemplateClicked( PaletteTemplate template )
	{
		Log.Info( $"{LogPrefix} PalettePanel.NotifyTemplateClicked: \"{template.Name}\"" );
		TemplateAddRequested?.Invoke( template );
	}

	internal void RequestTemplateDelete( PaletteTemplate template )
	{
		var dialog = new Editor.Dialog( this );
		dialog.Window.WindowTitle = "Delete template";
		dialog.Window.SetWindowIcon( "delete" );
		dialog.Window.SetModal( true, true );
		dialog.Window.MinimumWidth = 320;

		dialog.Layout = Layout.Column();
		dialog.Layout.Margin = 16;
		dialog.Layout.Spacing = 10;

		dialog.Layout.Add( new Editor.Label( dialog )
		{
			Text = $"Delete template \"{template.Name}\"?",
		} );

		var hint = new Editor.Label( dialog )
		{
			Text = "Already-instantiated copies in open documents are unaffected.",
		};
		hint.SetStyles( "color: #888; font-size: 11px;" );
		dialog.Layout.Add( hint );

		var buttonRow = dialog.Layout.Add( Layout.Row() );
		buttonRow.Spacing = 6;
		buttonRow.AddStretchCell();

		var cancel = new Editor.Button( dialog ) { Text = "Cancel", MinimumWidth = 72 };
		cancel.MouseLeftPress += () => dialog.Close();
		buttonRow.Add( cancel );

		var del = new Editor.Button( dialog ) { Text = "Delete", MinimumWidth = 72 };
		del.SetStyles( "color: #e07070;" );
		del.MouseLeftPress += () =>
		{
			Log.Info( $"{LogPrefix} Palette delete confirmed: \"{template.Name}\"" );
			_templateStore.Delete( template );
			dialog.Close();
		};
		buttonRow.Add( del );

		dialog.Window.AdjustSize();
		dialog.Show();
	}

	private void RebuildTemplatesSection()
	{
		var templates = _templateStore.All;

		// Hide the entire section (header + body) when there are no templates.
		_templatesSection.Visible = templates.Count > 0;

		using ( Editor.SuspendUpdates.For( _templatesWrap ) )
		{
			_templatesWrap.DestroyChildren();
			foreach ( var t in templates )
				new PaletteTemplateButton( _templatesWrap, this, t );
		}

		_templatesWrap.Relayout();
		_templatesWrap.UpdateGeometry();
		_templatesSection.UpdateGeometry();
		UpdateGeometry();

		Log.Info( $"{LogPrefix} PalettePanel.RebuildTemplatesSection: {templates.Count} tile(s), section.Visible={_templatesSection.Visible}" );
	}

	private static bool DefaultExpanded( ControlCategory cat ) =>
		cat is ControlCategory.Layout or ControlCategory.Display or ControlCategory.Input;

	private static string CategoryIcon( ControlCategory cat ) => cat switch
	{
		ControlCategory.Layout   => "view_quilt",
		ControlCategory.Display  => "visibility",
		ControlCategory.Input    => "edit",
		ControlCategory.Form     => "list_alt",
		_ => "category",
	};

	private sealed class PaletteTypeButton : Widget
	{
		private readonly PalettePanel _owner;
		private readonly ControlType _type;
		// InspectorIcon comes from the contract (engine-fidelity); drag defaults from ControlDefaults.
		private readonly string _icon;

		public PaletteTypeButton( Widget parent, PalettePanel owner, ControlType type ) : base( parent )
		{
			_owner = owner;
			_type = type;
			_icon = ContractScanner.Table.Get( type ).InspectorIcon;

			ToolTip = type.ToString();
			Cursor = CursorShape.Finger;
			MouseTracking = true;
			IsDraggable = true;
		}

		protected override void OnPaint()
		{
			var rect = LocalRect.Shrink( 1 );
			Paint.Antialiasing = true;
			Paint.TextAntialiasing = true;

			var tint = ControlPresentation.IconTint( _type );
			var fillAlpha = Paint.HasMouseOver ? 0.35f : 0.15f;
			var borderAlpha = Paint.HasMouseOver ? 0.55f : 0.25f;
			Paint.SetBrush( tint.WithAlpha( fillAlpha ) );
			Paint.SetPen( tint.WithAlpha( borderAlpha ) );
			Paint.DrawRect( rect, 3 );

			var hoverOpacity = Paint.HasMouseOver ? 1f : 0.85f;
			var iconRect = new Rect( rect.Left + 4, rect.Top, 20, rect.Height );
			Paint.SetPen( tint.WithAlphaMultiplied( hoverOpacity ) );
			Paint.DrawIcon( iconRect, _icon, 16, TextFlag.Center );

			var textRect = rect;
			textRect.Left = iconRect.Right + 2;
			textRect.Right -= 4;
			Paint.SetPen( Theme.Text.WithAlphaMultiplied( hoverOpacity ) );
			Paint.SetDefaultFont();
			Paint.DrawText( textRect, _type.ToString(), TextFlag.LeftCenter );
		}

		protected override void OnMouseClick( MouseEvent e )
		{
			base.OnMouseClick( e );
			if ( e.LeftMouseButton )
				_owner.NotifyTypeClicked( _type );
		}

		protected override void OnDragStart()
		{
			base.OnDragStart();

			var drag = new Drag( this );
			drag.Data.Object = _type;
			drag.Data.Text = $"palette:{_type}";
			drag.Execute();

			Log.Info( $"{LogPrefix} PaletteTypeButton.OnDragStart: {_type}" );
		}
	}

	private sealed class PaletteTemplateButton : Widget
	{
		private readonly PalettePanel _owner;
		private readonly PaletteTemplate _template;

		public PaletteTemplateButton( Widget parent, PalettePanel owner, PaletteTemplate template ) : base( parent )
		{
			_owner = owner;
			_template = template;

			ToolTip = template.Name;
			Cursor = CursorShape.Finger;
			MouseTracking = true;
			IsDraggable = true;
		}

		protected override void OnPaint()
		{
			var rect = LocalRect.Shrink( 1 );
			Paint.Antialiasing = true;
			Paint.TextAntialiasing = true;

			var tint = ControlPresentation.TemplateTint;
			var fillAlpha = Paint.HasMouseOver ? 0.18f : 0.08f;
			var borderAlpha = Paint.HasMouseOver ? 0.55f : 0.25f;
			Paint.SetBrush( tint.WithAlpha( fillAlpha ) );
			Paint.SetPen( tint.WithAlpha( borderAlpha ) );
			Paint.DrawRect( rect, 3 );

			var hoverOpacity = Paint.HasMouseOver ? 1f : 0.85f;
			var iconRect = new Rect( rect.Left + 4, rect.Top, 20, rect.Height );
			var icon = string.IsNullOrEmpty( _template.IconName ) ? "bookmark" : _template.IconName;
			Paint.SetPen( tint.WithAlphaMultiplied( hoverOpacity ) );
			Paint.DrawIcon( iconRect, icon, 16, TextFlag.Center );

			var textRect = rect;
			textRect.Left = iconRect.Right + 2;
			textRect.Right -= 4;
			Paint.SetPen( Theme.Text.WithAlphaMultiplied( hoverOpacity ) );
			Paint.SetDefaultFont();
			Paint.DrawText( textRect, _template.Name, TextFlag.LeftCenter );
		}

		protected override void OnMouseClick( MouseEvent e )
		{
			base.OnMouseClick( e );
			if ( e.LeftMouseButton )
				_owner.NotifyTemplateClicked( _template );
		}

		protected override void OnContextMenu( ContextMenuEvent e )
		{
			base.OnContextMenu( e );
			var menu = new Menu( this );
			menu.AddOption( "Delete…", "delete", () => _owner.RequestTemplateDelete( _template ) );
			menu.OpenAtCursor();
			e.Accepted = true;
		}

		protected override void OnDragStart()
		{
			base.OnDragStart();
			var drag = new Drag( this );
			drag.Data.Object = _template;
			drag.Data.Text = $"template:{_template.Name}";
			drag.Execute();
			Log.Info( $"{LogPrefix} PaletteTemplateButton.OnDragStart: \"{_template.Name}\"" );
		}
	}
}
namespace Grains.RazorDesigner.Projection.CSharp;

public abstract record CSharpOp;

// File-level scaffold
public sealed record HeaderBanner( string ClassName, string Namespace ) : CSharpOp;
public sealed record UsingDirective( string Namespace ) : CSharpOp;
public sealed record NamespaceOpen( string Namespace ) : CSharpOp;
public sealed record ClassOpen( string ClassName, string BaseClass ) : CSharpOp;
public sealed record ClassClose() : CSharpOp;

public sealed record FieldDecl(
    string Visibility, string Type, string Name, string InitialExpr,
    bool IsParameter, bool IsProperty = false ) : CSharpOp;

public sealed record MethodOpen(
    string Visibility, bool IsOverride, bool IsAsync,
    string ReturnType, string Name, string ParameterList ) : CSharpOp;

public sealed record MethodClose() : CSharpOp;

// Body-level
public sealed record Statement( string Code ) : CSharpOp;          // single `;`-terminated line
public sealed record BlockOpen( string Header ) : CSharpOp;        // e.g. `if ( <cond> )` — applier writes "<header> {\n" and indents
public sealed record BlockClose() : CSharpOp;
public sealed record BlankLine() : CSharpOp;
public sealed record Comment( string Text ) : CSharpOp;            // `// <text>`
using System.Collections.Generic;
using Grains.RazorDesigner.Projection.CSharp.Projectors;

namespace Grains.RazorDesigner.Projection.CSharp;

public static class CSharpProjector
{
    public static CSharpResult Project(
        IReadOnlyWiring wiring,
        bool documentHasAnyBindings )
    {
        if ( wiring.Symbols.Count == 0 && !documentHasAnyBindings )
            return new CSharpResult( System.Array.Empty<CSharpOp>(), null );

        var ctx = new CSharpProjectorContext( wiring );
        var ops = new List<CSharpOp>( 64 );

        ops.Add( new HeaderBanner( wiring.ClassName, wiring.Namespace ) );
        ops.Add( new UsingDirective( "Sandbox" ) );
        ops.Add( new UsingDirective( "Sandbox.UI" ) );
        foreach ( var u in wiring.Usings )
            ops.Add( new UsingDirective( u ) );
        ops.Add( new NamespaceOpen( wiring.Namespace ) );
        ops.Add( new ClassOpen( wiring.ClassName, wiring.BaseClass ) );

        // Step 3: body. SymbolProjector handles grouping + sorting + per-kind dispatch.
        SymbolProjector.EmitAll( wiring, ops, ctx );

        ops.Add( new ClassClose() );

        var source = CSharpApplier.Apply( ops ).Replace( "\r\n", "\n" );

        return new CSharpResult( ops, source );
    }
}
using System.Collections.Generic;
using Grains.RazorDesigner.Wiring;

namespace Grains.RazorDesigner.Projection.CSharp.Projectors;

public static class ParameterSymbolProjector
{
    public static void Emit( ParameterSymbol s, List<CSharpOp> ops, CSharpProjectorContext ctx )
    {
        var initial = s.Initial is null ? "default" : ExpressionEmitter.Emit( s.Initial, ctx );
        ops.Add( new FieldDecl(
            Visibility: "public", Type: s.Type, Name: s.Name,
            InitialExpr: initial, IsParameter: true ) );
    }
}
namespace Grains.RazorDesigner.Projection;

public static class Escape
{
    public static string Html( string s )
    {
        if ( string.IsNullOrEmpty( s ) ) return "";
        return s
            .Replace( "&", "&amp;" )
            .Replace( "<", "&lt;" )
            .Replace( ">", "&gt;" )
            .Replace( "\"", "&quot;" );
    }
}
using System;
using System.Collections.Generic;
using Sandbox; // Color

namespace Grains.RazorDesigner.Projection;

public interface IReadOnlyStateRule
{
    Document.PseudoKind State { get; }
    Document.NthChildMode NthChildMode { get; }
    int NthChildArg { get; }
    IAppearance Delta { get; }

    public static int CompareCanonical( IReadOnlyStateRule a, IReadOnlyStateRule b )
    {
        int c = ((int)a.State).CompareTo( (int)b.State );
        if ( c != 0 ) return c;
        c = ((int)a.NthChildMode).CompareTo( (int)b.NthChildMode );
        if ( c != 0 ) return c;
        return a.NthChildArg.CompareTo( b.NthChildArg );
    }
}

public interface IReadOnlyNode
{
    Guid Id { get; }
    string Kind { get; }         // == ControlType.ToString()
    string ClassName { get; }
    IAppearance Appearance { get; }
    IPayload Payload { get; }
    IReadOnlyList<IReadOnlyNode> Children { get; }                              // non-slot children
    IReadOnlyDictionary<string, IReadOnlyList<IReadOnlyNode>> Slots { get; }    // slot-name -> slot children (only SplitContainer populates)
    IReadOnlyList<IReadOnlyStateRule> StateRules { get; }                       // per-state style deltas; canonical order not guaranteed here (the Applier sorts)
}

public interface IAppearance
{
    // Layout
    Document.Length Width { get; }
    Document.Length Height { get; }

    // Flex container
    Document.FlexDirection Direction { get; }
    Document.JustifyContent Justify { get; }
    Document.AlignItems Align { get; }
    float Gap { get; }
    Document.Edges Padding { get; }
    Document.FlexWrap Wrap { get; }

    // Positioning (grd-7t2z)
    Document.PositionKind Position { get; }
    Document.Length Top { get; }
    Document.Length Left { get; }
    Document.Length Right { get; }
    Document.Length Bottom { get; }

    // Flex self
    float FlexGrow { get; }
    float FlexShrink { get; }
    Document.Length FlexBasis { get; }
    Document.AlignSelfKind AlignSelf { get; }

    // Typography + OverrideTypography
    bool OverrideTypography { get; }
    string FontFamily { get; }
    Document.Length FontSize { get; }
    int FontWeight { get; }
    Color Color { get; }
    Document.TextAlignment TextAlign { get; }
    bool FontStyleItalic { get; }
    Document.TextTransformKind TextTransform { get; }
    Document.Length LetterSpacing { get; }
    Document.Length LineHeight { get; }

    // Background + OverrideBackground
    bool OverrideBackground { get; }
    Color BackgroundColor { get; }
    string BackgroundImage { get; }
    string BackgroundSize { get; }
    string BackgroundPosition { get; }
    string BackgroundRepeat { get; }

    // Border + OverrideBorder
    bool OverrideBorder { get; }
    Document.Length BorderRadius { get; }
    Color BorderColor { get; }
    Document.Length BorderWidth { get; }

    // Effects + OverrideEffects
    bool OverrideEffects { get; }
    Document.Length BoxShadowX { get; }
    Document.Length BoxShadowY { get; }
    Document.Length BoxShadowBlur { get; }
    Color BoxShadowColor { get; }
    bool BoxShadowInset { get; }
    float Opacity { get; }

    // Constraints + OverrideConstraints
    bool OverrideConstraints { get; }
    Document.Edges Margin { get; }
    Document.Length MinWidth { get; }
    Document.Length MaxWidth { get; }
    Document.Length MinHeight { get; }
    Document.Length MaxHeight { get; }

    // Interaction + OverrideInteraction
    bool OverrideInteraction { get; }
    Document.CursorKind Cursor { get; }
    Document.OverflowKind Overflow { get; }
    int ZIndex { get; }
    bool PointerEvents { get; }
}

public interface IPayload
{
    string Content { get; }       // Label/Button text; Checkbox label
    string Placeholder { get; }   // TextEntry
    string Source { get; }        // Image src
    string IconName { get; }      // IconPanel glyph
    Document.Length CheckboxSize { get; }  // Checkbox box size
}
using System.Collections.Generic;
using Grains.RazorDesigner.Projection.Appearance;
using Grains.RazorDesigner.Projection.Razor;

namespace Grains.RazorDesigner.Projection.Projectors;

[Projector( "Button" )]
public sealed class ButtonProjector : IControlProjector
{
    public string Kind => "Button";

    public ProjectionResult Project( IReadOnlyNode node, IAppearance a, IPayload p, ProjectionContext ctx )
    {
        var scss = AppearanceScss.Emit(
            a,
            isRoot:       node.ClassName == Document.DesignerDocument.RootClassName,
            isContainer:  false,
            childCount:   0,
            isLabel:      false,
            isCheckbox:   false,
            checkboxSize: default );

        var nodeId = node.Id.ToString();
        var ops = new PanelOp[]
        {
            new SetAttribute( "data-grd-node-id", nodeId ),
            new SetInnerText( p.Content ?? "" ),
        };

        var razorAttrs = new[] { RazorEmit.Attr( "data-grd-node-id", nodeId ) };

        return new ProjectionResult(
            PanelOps:        ops,
            ScssLines:       scss,
            RazorAttributes: razorAttrs,
            RazorInnerText:  Escape.Html( p.Content ?? "" ) );
    }
}
using System.Collections.Generic;
using Grains.RazorDesigner.Projection.Appearance;
using Grains.RazorDesigner.Projection.Razor;

namespace Grains.RazorDesigner.Projection.Projectors;

[Projector( "Field" )]
public sealed class FieldProjector : IControlProjector
{
    public string Kind => "Field";

    public ProjectionResult Project( IReadOnlyNode node, IAppearance a, IPayload p, ProjectionContext ctx )
    {
        var scss = AppearanceScss.Emit(
            a,
            isRoot:       node.ClassName == Document.DesignerDocument.RootClassName,
            isContainer:  true,
            childCount:   node.Children.Count,
            isLabel:      false,
            isCheckbox:   false,
            checkboxSize: default );

        var nodeId = node.Id.ToString();
        var ops = new PanelOp[]
        {
            new SetAttribute( "data-grd-node-id", nodeId ),
        };

        var razorAttrs = new[] { RazorEmit.Attr( "data-grd-node-id", nodeId ) };

        return new ProjectionResult(
            PanelOps:        ops,
            ScssLines:       scss,
            RazorAttributes: razorAttrs,
            RazorInnerText:  null );
    }
}
namespace Grains.RazorDesigner.Projection.Razor;

public static class RazorEmit
{
    public static string Attr( string name, string value ) => $"{name}=\"{Escape.Html( value )}\"";
}