Editor/TerrainMaterialTools.cs

Editor MCP toolset for terrain materials, exposes tools to add and remove .tmat materials, query and paint materials and blends, and cut or fill holes. Changes are recorded as editor undo steps.

using System;
using System.IO;
using System.Linq;
using Editor;
using Editor.Mcp;
using Sandbox;
using static LevelTools.McpHelpers;
using static LevelTools.TerrainEdit;

namespace LevelTools;

[McpToolset( "terrain" )]
public static class TerrainMaterialTools
{
    // The control map packs material indices into 5 bits
    const int MaxMaterials = 32;

    /// <summary>
    /// Add a terrain material (.tmat) to a terrain's material list. Its index is what terrain_paint_material
    /// and terrain_blend_materials paint with; a material already in the list keeps its index. The user
    /// can undo this. Find materials with asset_search type:tmat.
    /// </summary>
    /// <param name="materialPath">Terrain material asset path, e.g. 'materials/terrain/snow_02.tmat'.</param>
    /// <param name="id">Terrain game object id. Empty means the scene's only terrain.</param>
    [McpTool( "terrain_add_material" )]
    public static object AddMaterial( string materialPath, string id = "" )
    {
        var (terrain, session) = ForEdit( id );
        var materials = terrain.Storage.Materials;

        var material = ResourceLibrary.Get<TerrainMaterial>( materialPath )
            ?? throw new Exception( $"No terrain material at '{materialPath}' - asset_search type:tmat lists them" );

        var index = materials.IndexOf( material );
        if ( index < 0 )
        {
            if ( materials.Count >= MaxMaterials )
                throw new Exception( $"The terrain already has {MaxMaterials} materials, the most it can paint with - remove one with terrain_remove_material" );

            materials.Add( material );
            index = materials.Count - 1;
            terrain.UpdateMaterialsBuffer();
            AddUndo( session, terrain, "Add Terrain Material", t => t.Storage.Materials.Remove( material ), t => t.Storage.Materials.Add( material ) );
        }

        return new { Id = terrain.GameObject.Id, Index = index, Name = material.ResourceName, MaterialCount = materials.Count };
    }

    /// <summary>
    /// Remove a material from a terrain's list. Later materials move down one index but painted texels
    /// keep theirs, so texels of each later material now show the next one in the list, or nothing past
    /// its end - repaint them with terrain_paint_material. The user can undo this.
    /// </summary>
    /// <param name="material">The material's index, name or asset path, as terrain_get_info lists them.</param>
    /// <param name="id">Terrain game object id. Empty means the scene's only terrain.</param>
    [McpTool( "terrain_remove_material" )]
    public static object RemoveMaterial( string material, string id = "" )
    {
        var (terrain, session) = ForEdit( id );
        var index = MaterialIndex( terrain, material );
        var removed = terrain.Storage.Materials[index];

        terrain.Storage.Materials.RemoveAt( index );
        terrain.UpdateMaterialsBuffer();
        AddUndo( session, terrain, "Remove Terrain Material", t => t.Storage.Materials.Insert( index, removed ), t => t.Storage.Materials.RemoveAt( index ) );

        return new { Id = terrain.GameObject.Id, RemovedIndex = index, RemovedName = removed?.ResourceName, MaterialCount = terrain.Storage.Materials.Count };
    }

    /// <summary>
    /// The materials at a world position: the base and overlay material with their indices, the blend
    /// between them (0 all base, 1 all overlay), which one dominates, and whether the spot is a hole.
    /// </summary>
    /// <param name="position">World position as 'x,y,z'. Only x and y matter.</param>
    /// <param name="id">Terrain game object id. Empty means the scene's only terrain.</param>
    [McpTool.ReadOnly( "terrain_get_material_at" )]
    public static object GetMaterialAt( Vector3 position, string id = "" )
    {
        var terrain = ForRead( id );

        // The engine accepts the far edge itself and reads one texel past the row there, so its bounds are checked here first
        RequireTexel( terrain, position );
        var info = terrain.GetMaterialAtWorldPosition( position )
            ?? throw new Exception( $"{position} is off the terrain '{terrain.GameObject.Name}' - terrain_get_info shows its position and size" );

        return new
        {
            Id = terrain.GameObject.Id,
            BaseIndex = info.BaseTextureId,
            BaseMaterial = info.BaseMaterial?.ResourceName,
            OverlayIndex = info.OverlayTextureId,
            OverlayMaterial = info.OverlayMaterial?.ResourceName,
            Blend = MathF.Round( info.BlendFactor, 3 ),
            Dominant = info.GetDominantMaterial()?.ResourceName,
            info.IsHole
        };
    }

    /// <summary>
    /// Paint one material solidly over a circle, replacing whatever base, overlay and blend were there.
    /// Holes are kept. The user can undo this. Check with terrain_get_material_at.
    /// </summary>
    /// <param name="position">Brush centre as 'x,y,z'.</param>
    /// <param name="material">The material's index, name or asset path, as terrain_get_info lists them. Only indices 0 to 31 can be painted.</param>
    /// <param name="radius">Brush radius in units.</param>
    /// <param name="id">Terrain game object id. Empty means the scene's only terrain.</param>
    [McpTool( "terrain_paint_material" )]
    public static object PaintMaterial( Vector3 position, string material, float radius = 50f, string id = "" )
    {
        var (terrain, session) = ForEdit( id );
        var index = PaintIndex( terrain, material );

        var changed = EditControl( session, terrain, "Terrain Paint", position, radius, c => new CompactTerrainMaterial( index, index, 0, c.IsHole ) );

        return new { Id = terrain.GameObject.Id, Index = index, Name = terrain.Storage.Materials[index]?.ResourceName, TexelsChanged = changed };
    }

    /// <summary>
    /// Set a two-material blend over a circle: a base material, an overlay material and how much of the
    /// overlay shows. Holes are kept. The user can undo this. Check with terrain_get_material_at.
    /// </summary>
    /// <param name="position">Brush centre as 'x,y,z'.</param>
    /// <param name="baseIndex">Index of the base material, from terrain_get_info. Only indices 0 to 31 can be painted.</param>
    /// <param name="overlayIndex">Index of the overlay material.</param>
    /// <param name="blend">0 shows only the base, 1 only the overlay.</param>
    /// <param name="radius">Brush radius in units.</param>
    /// <param name="id">Terrain game object id. Empty means the scene's only terrain.</param>
    [McpTool( "terrain_blend_materials" )]
    public static object BlendMaterials( Vector3 position, int baseIndex = 0, int overlayIndex = 1, [Sandbox.Range( 0, 1 )] float blend = 0.5f,
        float radius = 50f, string id = "" )
    {
        var (terrain, session) = ForEdit( id );
        RequireFinite( "blend", blend );
        var b = PaintIndex( terrain, baseIndex.ToString() );
        var o = PaintIndex( terrain, overlayIndex.ToString() );
        var amount = (byte)Math.Clamp( (int)(blend * 255f), 0, 255 );

        var changed = EditControl( session, terrain, "Terrain Blend", position, radius, c => new CompactTerrainMaterial( b, o, amount, c.IsHole ) );

        return new { Id = terrain.GameObject.Id, BaseIndex = b, OverlayIndex = o, Blend = amount / 255f, TexelsChanged = changed };
    }

    /// <summary>
    /// Cut a hole through the terrain over a circle, or fill one back in. Holes don't render and nothing
    /// collides with them - use them for cave mouths and tunnels. Painted materials are kept. The user
    /// can undo this.
    /// </summary>
    /// <param name="position">Brush centre as 'x,y,z'.</param>
    /// <param name="radius">Brush radius in units.</param>
    /// <param name="enabled">True cuts a hole, false fills it.</param>
    /// <param name="id">Terrain game object id. Empty means the scene's only terrain.</param>
    [McpTool( "terrain_set_hole" )]
    public static object SetHole( Vector3 position, float radius = 10f, bool enabled = true, string id = "" )
    {
        var (terrain, session) = ForEdit( id );

        var changed = EditControl( session, terrain, enabled ? "Terrain Hole" : "Terrain Fill Hole", position, radius, c => c with { IsHole = enabled } );

        return new { Id = terrain.GameObject.Id, Hole = enabled, TexelsChanged = changed };
    }

    static int EditControl( SceneEditorSession session, Terrain terrain, string undoName, Vector3 position, float radius,
        Func<CompactTerrainMaterial, CompactTerrainMaterial> change )
    {
        var map = terrain.Storage.ControlMap;
        var brush = BrushAt( terrain, position, radius );

        var changed = 0;
        CommitControl( session, terrain, undoName, brush.Region,
            () => changed = brush.ForEach( ( i, _, _, _ ) => map[i] = change( new CompactTerrainMaterial( map[i] ) ).Packed ) );

        return changed;
    }

    // A list edited in the inspector can hold more materials than the control map can address; removing them stays allowed
    static byte PaintIndex( Terrain terrain, string material )
    {
        var index = MaterialIndex( terrain, material );
        return index < MaxMaterials ? (byte)index
            : throw new Exception( $"Material {index} can't be painted - the control map stores 5-bit indices, so only the first {MaxMaterials} materials (0 to {MaxMaterials - 1}) can be painted; remove materials with terrain_remove_material to move it down" );
    }

    static int MaterialIndex( Terrain terrain, string material )
    {
        var materials = terrain.Storage.Materials;

        if ( materials.Count == 0 )
            throw new Exception( $"'{terrain.GameObject.Name}' has no materials yet - add one with terrain_add_material" );

        if ( int.TryParse( material, out var index ) )
        {
            return index >= 0 && index < materials.Count ? index
                : throw new Exception( $"Material index {index} is out of range - '{terrain.GameObject.Name}' has materials 0 to {materials.Count - 1}" );
        }

        bool Matches( string value ) => string.Equals( value, material, StringComparison.OrdinalIgnoreCase );

        var found = materials.FindIndex( m => m is not null
            && (Matches( m.ResourceName ) || Matches( m.ResourcePath ) || Matches( Path.GetFileNameWithoutExtension( m.ResourcePath ) )) );

        return found >= 0 ? found
            : throw new Exception( $"'{material}' isn't one of the terrain's materials ({string.Join( ", ", materials.Select( ( m, i ) => $"{i} {m?.ResourceName}" ) )}) - add it with terrain_add_material" );
    }

    // Material lists are small, so undo replays the list change itself; the terrain is resolved by id as in TerrainEdit.Commit
    static void AddUndo( SceneEditorSession session, Terrain terrain, string name, Action<Terrain> undo, Action<Terrain> redo )
    {
        var scene = session.Scene;
        var componentId = terrain.Id;

        Action Apply( Action<Terrain> change ) => () =>
        {
            if ( scene.Directory.FindComponentByGuid( componentId ) is not Terrain target || target.Storage is null )
                return;

            change( target );
            target.UpdateMaterialsBuffer();
        };

        session.AddUndo( name, Apply( undo ), Apply( redo ) );
        session.HasUnsavedChanges = true;
    }
}