Editor/Tilemap/TilemapManualPalette.cs

The TilemapManualPalette widget manages and displays a selection of tiles from a manual tileset. It organizes tiles into sections for recent usage, favorites, and all tiles, allowing the editor user to select tiles for use in a map.

File Access
using System;
using Saandy.Tilemapper;

namespace Saandy.Editor.Tilemapper;

/// <summary>Scene-local tile selection. Selecting a thumbnail never edits the tileset asset.</summary>
internal sealed class TilemapManualPalette : Widget
{
	private readonly OverlayText Selection;
	private readonly ScrollArea Scroll;
	private readonly TileGrid Grid;
	private readonly TileGrid RecentGrid;
	private readonly TileGrid FavouriteGrid;
	private readonly OverlayText RecentHint;
	private readonly OverlayText FavouriteHint;
	private readonly Action<bool> OpenChanged;
	private TilesetResource CurrentTileset;
	private int CurrentRevision = -1;
	private ushort CurrentIndex;
	private Guid[] RecentIds = Array.Empty<Guid>();
	private bool Available;
	public bool IsOpen => Visible;
	public bool RequiresRebuild { get; private set; }

	[EditorEvent.Hotload]
	private void OnHotload() => RequiresRebuild = true;

	public TilemapManualPalette( Action<ushort> selectTile, Action<bool> openChanged )
	{
		OpenChanged = openChanged;
		NoSystemBackground = true;
		TranslucentBackground = true;
		Visible = false;
		Layout = Layout.Column();
		Layout.Margin = 10;
		Layout.Spacing = 6;
		SetStyles( "background-color: transparent;" );
		Scroll = Layout.Add( new ScrollArea( this )
		{
			HorizontalSizeMode = SizeMode.Flexible,
			VerticalSizeMode = SizeMode.Flexible,
			NoSystemBackground = true,
			TranslucentBackground = true,
			HorizontalScrollbarMode = ScrollbarMode.Off,
			VerticalScrollbarMode = ScrollbarMode.Auto
		}, 1 );
		Scroll.SetStyles( "* { background-color: transparent; border: none; } QScrollBar::handle:vertical { background-color: rgba(190, 190, 190, 150); border-radius: 3px; min-height: 24px; }" );
		var content = new Widget( Scroll )
		{
			Layout = Layout.Column(),
			VerticalSizeMode = SizeMode.CanGrow,
			HorizontalSizeMode = SizeMode.Flexible,
			NoSystemBackground = true,
			TranslucentBackground = true
		};
		content.Layout.Spacing = 6;
		content.Layout.Alignment = TextFlag.Top;
		Scroll.Canvas = content;
		content.NoSystemBackground = true;
		content.SetStyles( "* { background-color: transparent; }" );
		AddSectionTitle( content, "RECENT" );
		RecentGrid = content.Layout.Add( new TileGrid( Scroll, selectTile, ToggleFavourite ) );
		RecentHint = content.Layout.Add( new OverlayText( "Paint with a tile to add it here." ) );
		AddSectionTitle( content, "FAVOURITES" );
		FavouriteGrid = content.Layout.Add( new TileGrid( Scroll, selectTile, ToggleFavourite ) );
		FavouriteHint = content.Layout.Add( new OverlayText( "Right-click any tile to favourite it." ) );
		AddSectionTitle( content, "ALL TILES" );
		Grid = content.Layout.Add( new TileGrid( Scroll, selectTile, ToggleFavourite ) );
		Selection = Layout.Add( new OverlayText( "" ) );
		ToolTip = "Hold SHIFT to choose a tile. Left-click selects; right-click toggles a favourite.";
	}

	private static void AddSectionTitle( Widget content, string text )
	{
		content.Layout.Add( new OverlayText( text, true ) );
	}

	public void SetTileset( TilesetResource tileset, ushort index, IReadOnlyList<Guid> recent )
	{
		Available = tileset != null && tileset.IsValid() && tileset.BrushType == BrushType.Manual && !Game.IsPlaying;
		if ( !Available ) { SetOpen( false ); return; }
		if ( CurrentTileset != tileset || CurrentRevision != tileset.RenderRevision || CurrentIndex != index || !RecentIds.SequenceEqual( recent ) )
		{
			CurrentTileset = tileset;
			CurrentRevision = tileset.RenderRevision;
			CurrentIndex = index;
			RecentIds = recent.ToArray();
			var all = Enumerable.Range( 0, Math.Min( tileset.Tiles?.Count ?? 0, ushort.MaxValue + 1 ) )
				.Where( i => tileset.Tiles[i] != null ).Select( i => (ushort)i ).ToList();
			var favourites = all.Where( i => tileset.Tiles[i].IsFavourite ).ToList();
			var byId = all.Where( i => tileset.Tiles[i].Id != Guid.Empty ).GroupBy( i => tileset.Tiles[i].Id ).ToDictionary( group => group.Key, group => group.First() );
			var recentIndices = RecentIds.Where( byId.ContainsKey ).Select( id => byId[id] ).ToList();
			Grid.Bind( tileset, index, all );
			FavouriteGrid.Bind( tileset, index, favourites );
			RecentGrid.Bind( tileset, index, recentIndices );
			FavouriteGrid.Visible = favourites.Count > 0;
			FavouriteHint.Visible = favourites.Count == 0;
			RecentGrid.Visible = recentIndices.Count > 0;
			RecentHint.Visible = recentIndices.Count == 0;
		}
		Selection.Text = tileset.Tiles?.Count > 0
			? $"{TileLabel( tileset, index )}     |     LMB select · RMB favourite"
			: "No tiles defined. Open the tileset editor to add rectangles.";
		UpdateOpenState();
	}

	private static string TileLabel( TilesetResource tileset, ushort index )
	{
		var label = $"Tile {index}";
		var name = tileset.Tiles[index]?.Name?.Trim();
		return string.IsNullOrEmpty( name ) || string.Equals( name, label, StringComparison.OrdinalIgnoreCase )
			? label : $"{label} · {name}";
	}

	private void ToggleFavourite( ushort index )
	{
		if ( CurrentTileset == null || index >= (CurrentTileset.Tiles?.Count ?? 0) || CurrentTileset.Tiles[index] == null ) { return; }
		CurrentTileset.Tiles[index].IsFavourite = !CurrentTileset.Tiles[index].IsFavourite;
		CurrentTileset.InternalUpdateTiles();
		var asset = AssetSystem.FindByPath( CurrentTileset.ResourcePath );
		if ( asset == null || !asset.SaveToDisk( CurrentTileset ) )
		{
			Log.Warning( $"Unable to save tile favourites for '{CurrentTileset.ResourcePath}'. Check that the tileset asset is writable." );
		}
		CurrentTileset.StateHasChanged();
		SetTileset( CurrentTileset, CurrentIndex, RecentIds );
	}

	private void SetOpen( bool open )
	{
		if ( Visible == open ) { return; }
		Visible = open;
		OpenChanged( open );
		if ( open ) { Scroll.VerticalScrollbar.Value = 0; Anchor(); }
	}

	private void UpdateOpenState()
	{
		var modifiers = global::Editor.Application.KeyboardModifiers;
		SetOpen( Available && !Game.IsPlaying && modifiers.HasFlag( KeyboardModifiers.Shift ) && !modifiers.HasFlag( KeyboardModifiers.Alt ) );
	}

	[EditorEvent.Frame]
	private void Anchor()
	{
		UpdateOpenState();
		if ( !Parent.IsValid() || !Visible ) { return; }
		float width = Math.Max( 1, MathF.Floor( Parent.Width ) );
		float height = Math.Max( 1, MathF.Floor( Parent.Height ) );
		if ( FixedWidth != width || FixedHeight != height )
		{
			FixedWidth = width;
			FixedHeight = height;
		}
		Position = Vector2.Zero;
	}

	protected override void OnMousePress( MouseEvent e ) { e.Accepted = true; }

	protected override void OnPaint() { }

	/// <summary>Draw text directly, without the editor theme's opaque label background.</summary>
	private sealed class OverlayText : Widget
	{
		private string Value;
		private readonly bool Heading;
		public string Text
		{
			get => Value;
			set { if ( Value == value ) { return; } Value = value; Update(); }
		}
		public OverlayText( string text, bool heading = false )
		{
			Value = text;
			Heading = heading;
			FixedHeight = 20;
			HorizontalSizeMode = SizeMode.Flexible;
			NoSystemBackground = true;
			TranslucentBackground = true;
			SetStyles( "background-color: transparent;" );
		}
		protected override void OnPaint()
		{
			Paint.SetDefaultFont( 10, Heading ? 600 : 400 );
			Paint.SetPen( Color.Black.WithAlpha( 0.9f ) );
			Paint.DrawText( new Rect( 1, 1, Width - 1, Height - 1 ), Value, TextFlag.LeftCenter );
			Paint.SetPen( Color.White.WithAlpha( Heading ? 1 : 0.85f ) );
			Paint.DrawText( LocalRect, Value, TextFlag.LeftCenter );
			Paint.SetDefaultFont();
		}
	}

	private sealed class TileGrid : Widget
	{
		private const int CellSize = 56;
		private const int Padding = 4;
		private readonly ScrollArea Scroll;
		private readonly Action<ushort> SelectTile;
		private readonly Action<ushort> FavouriteTile;
		private readonly List<ushort> Indices = new();
		private readonly Dictionary<int, Pixmap> Thumbnails = new();
		private readonly Dictionary<int, Pixmap> Shadows = new();
		private readonly Dictionary<(int Index, int Width, int Height), Pixmap> Halos = new();
		private TilesetResource Tileset;
		private Pixmap Source;
		private int Revision = -1;
		private int Count;
		private ushort Selected;
		private int Hovered = -1;
		private int Columns => Math.Max( 1, (int)((Width - Padding * 2) / CellSize) );

		public TileGrid( ScrollArea scroll, Action<ushort> selectTile, Action<ushort> favouriteTile ) : base( scroll )
		{
			Scroll = scroll;
			SelectTile = selectTile;
			FavouriteTile = favouriteTile;
			MouseTracking = true;
			NoSystemBackground = true;
			TranslucentBackground = true;
			SetStyles( "background-color: transparent;" );
			HorizontalSizeMode = SizeMode.Flexible;
		}

		public void Bind( TilesetResource tileset, ushort index, IReadOnlyList<ushort> indices )
		{
			if ( Tileset == tileset && Revision == tileset.RenderRevision && Indices.SequenceEqual( indices ) && Selected == index ) { return; }
			if ( Tileset != tileset || Revision != tileset.RenderRevision )
			{
				Tileset = tileset;
				Revision = tileset.RenderRevision;
				Thumbnails.Clear();
				Shadows.Clear();
				Halos.Clear();
				var texture = tileset.GetTexture();
				Source = texture != null && texture.IsValid ? Pixmap.FromTexture( texture, true ) : null;
			}
			Indices.Clear();
			Indices.AddRange( indices );
			Hovered = -1;
			Count = Indices.Count;
			Selected = index;
			ResizeCanvas();
			Update();
		}

		protected override void OnResize() { base.OnResize(); ResizeCanvas(); }
		private void ResizeCanvas()
		{
			float height = Math.Max( CellSize, ((Count + Columns - 1) / Columns) * CellSize + Padding * 2 );
			if ( FixedHeight != height ) { FixedHeight = height; }
		}
		private Rect CellRect( int index ) => new( Padding + index % Columns * CellSize, Padding + index / Columns * CellSize, CellSize - 4, CellSize - 4 );
		private int IndexAt( Vector2 position )
		{
			int col = (int)MathF.Floor( (position.x - Padding) / CellSize );
			int row = (int)MathF.Floor( (position.y - Padding) / CellSize );
			int index = row * Columns + col;
			return col >= 0 && col < Columns && row >= 0 && index < Count && CellRect( index ).IsInside( position ) ? index : -1;
		}
		protected override void OnMousePress( MouseEvent e )
		{
			base.OnMousePress( e );
			int index = IndexAt( e.LocalPosition );
			if ( index < 0 ) { return; }
			e.Accepted = true;
			if ( e.LeftMouseButton ) { SelectTile( Indices[index] ); }
			else if ( e.Button == MouseButtons.Right ) { FavouriteTile( Indices[index] ); }
		}
		protected override void OnMouseMove( MouseEvent e )
		{
			base.OnMouseMove( e );
			int index = IndexAt( e.LocalPosition );
			if ( Hovered != index ) { Hovered = index; Update(); }
			ToolTip = index >= 0 ? $"{TileLabel( Tileset, Indices[index] )}\nRight-click to favourite/unfavourite." : "";
		}
		protected override void OnMouseLeave()
		{
			base.OnMouseLeave();
			Hovered = -1;
			ToolTip = "";
			Update();
		}
		protected override void OnPaint()
		{
			if ( Tileset == null ) { return; }
			float top = FromScreen( Scroll.ScreenPosition ).y;
			int first = Math.Max( 0, (int)(top / CellSize) * Columns );
			int end = Math.Min( Count, ((int)((top + Scroll.Height) / CellSize) + 2) * Columns );
			for ( int i = first; i < end; i++ )
			{
				var rect = CellRect( i );
				int tileIndex = Indices[i];
				var thumbnail = Thumbnail( tileIndex );
				if ( thumbnail != null )
				{
					float scale = Math.Min( (rect.Width - 8) / thumbnail.Width, (rect.Height - 8) / thumbnail.Height );
					float w = thumbnail.Width * scale, h = thumbnail.Height * scale;
					var imageRect = new Rect( rect.Left + (rect.Width - w) * 0.5f, rect.Top + (rect.Height - h) * 0.5f, w, h );
					var shadow = Shadow( tileIndex, thumbnail );
					if ( shadow != null )
					{
						var halo = Halo( tileIndex, shadow, w, h );
						Paint.Draw( new Rect( imageRect.Left - 8, imageRect.Top - 8, w + 16, h + 16 ), halo );
					}
					Paint.Draw( imageRect, thumbnail );
					Paint.ClearBrush();
					Paint.SetPen( tileIndex == Selected ? Color.Green : Color.White.WithAlpha( i == Hovered ? 0.95f : 0.4f ), tileIndex == Selected ? 2.0f : 1.0f );
					Paint.DrawRect( imageRect );
				}
				if ( Tileset.Tiles[tileIndex].IsFavourite )
				{
					Paint.SetDefaultFont( 10 );
					Paint.SetPen( Color.Yellow );
					Paint.DrawText( new Rect( rect.Right - 15, rect.Top + 1, 14, 14 ), "★", TextFlag.Center );
				}
			}
			Paint.SetDefaultFont();
		}

		private Pixmap Halo( int index, Pixmap shadow, float width, float height )
		{
			int w = Math.Max( 1, (int)MathF.Ceiling( width ) );
			int h = Math.Max( 1, (int)MathF.Ceiling( height ) );
			var key = (index, w, h);
			if ( Halos.TryGetValue( key, out var cached ) ) { return cached; }
			var result = new Pixmap( w + 16, h + 16 );
			result.Clear( Color.Transparent );
			using ( Paint.ToPixmap( result ) )
			{
				// Symmetric rings spread out evenly, rather than casting down/right.
				for ( int ring = 4; ring >= 1; ring-- )
				{
					float alpha = ring == 1 ? 0.32f : ring == 2 ? 0.22f : ring == 3 ? 0.14f : 0.08f;
					for ( int y = -1; y <= 1; y++ )
					for ( int x = -1; x <= 1; x++ )
					{
						if ( x == 0 && y == 0 ) { continue; }
						Paint.Draw( new Rect( 8 + x * ring * 2, 8 + y * ring * 2, w, h ), shadow, alpha );
					}
				}
			}
			Halos[key] = result;
			return result;
		}

		private Pixmap Shadow( int index, Pixmap source )
		{
			if ( Shadows.TryGetValue( index, out var cached ) ) { return cached; }
			// Cache a small black alpha silhouette, preserving transparent tile shapes.
			float scale = Math.Min( 1, 64.0f / Math.Max( source.Width, source.Height ) );
			int width = Math.Max( 1, (int)MathF.Ceiling( source.Width * scale ) );
			int height = Math.Max( 1, (int)MathF.Ceiling( source.Height * scale ) );
			byte[] pixels = new byte[width * height * 4];
			for ( int y = 0; y < height; y++ )
			for ( int x = 0; x < width; x++ )
			{
				pixels[(y * width + x) * 4 + 3] = (byte)Math.Clamp( source.GetPixel( x * source.Width / width, y * source.Height / height ).a * 255, 0, 255 );
			}
			var result = new Pixmap( width, height );
			result.UpdateFromPixels( pixels, width, height, ImageFormat.RGBA8888 );
			Shadows[index] = result;
			return result;
		}
		private Pixmap Thumbnail( int index )
		{
			if ( Thumbnails.TryGetValue( index, out var cached ) ) { return cached; }
			var tile = Tileset.Tiles[index];
			if ( Source == null || tile == null || tile.SourceRect.Width <= 0 || tile.SourceRect.Height <= 0 ) { return null; }
			int x = Math.Clamp( (int)MathF.Floor( tile.SourceRect.Left ), 0, Source.Width );
			int y = Math.Clamp( (int)MathF.Floor( tile.SourceRect.Top ), 0, Source.Height );
			int right = Math.Clamp( (int)MathF.Ceiling( tile.SourceRect.Right ), x, Source.Width );
			int bottom = Math.Clamp( (int)MathF.Ceiling( tile.SourceRect.Bottom ), y, Source.Height );
			if ( right <= x || bottom <= y ) { return null; }
			var result = new Pixmap( right - x, bottom - y );
			result.Clear( Color.Transparent );
			using ( Paint.ToPixmap( result ) ) { Paint.Draw( new Rect( -x, -y, Source.Width, Source.Height ), Source ); }
			Thumbnails[index] = result;
			return result;
		}
	}
}