Editor/TerrainEdit.cs

Editor helpers for the terrain tools: brushes texels within a circular radius, resolves a terrain by id, maps world positions to texels, and commits height/control map edits with undo.

🐞 Copy and the restore loop index rows by `region.Top + y`, but `RectInt.Top` is the rectangle's top edge (the max y), not the minimum y, so the wrong rows are copied and written back
using System;
using System.Linq;
using Editor;
using Sandbox;
using static LevelTools.McpHelpers;

namespace LevelTools;

/// <summary>
/// The texels a circular brush covers. Region is the clamped bounding rectangle, the unit of undo.
/// </summary>
internal readonly record struct TerrainBrush( Vector2Int Centre, int Radius, RectInt Region, int Resolution )
{
    /// <summary>Visit each texel inside the circle with its index, offset from the centre and distance (0 centre, 1 rim).</summary>
    public int ForEach( Action<int, int, int, float> visit )
    {
        var count = 0;
        for ( var y = Region.Top; y < Region.Top + Region.Height; y++ )
        {
            for ( var x = Region.Left; x < Region.Left + Region.Width; x++ )
            {
                int dx = x - Centre.x, dy = y - Centre.y;
                var distance = MathF.Sqrt( dx * dx + dy * dy );
                if ( distance > Radius ) continue;

                visit( y * Resolution + x, dx, dy, distance / Radius );
                count++;
            }
        }

        return count;
    }
}

internal static class TerrainEdit
{
    internal static RectInt Whole( Terrain terrain ) => new( 0, 0, terrain.Storage.Resolution, terrain.Storage.Resolution );

    internal static Terrain ForRead( string id ) => Find( id, ReadScene() );

    internal static (Terrain Terrain, SceneEditorSession Session) ForEdit( string id )
    {
        var terrain = Find( id, ActiveSession().Scene );

        // A disabled terrain has no GPU textures, so its edits could not be shown or collided with
        if ( !terrain.Active )
            throw new Exception( $"'{terrain.GameObject.Name}' is disabled - enable it with set_game_object before editing it" );

        return (terrain, SessionOf( terrain.GameObject ));
    }

    // An empty id means the scene's only terrain, the usual case
    static Terrain Find( string id, Scene scene )
    {
        Terrain terrain;

        if ( !string.IsNullOrWhiteSpace( id ) )
        {
            var go = FindByGuid( id );
            terrain = go.Components.Get<Terrain>( FindMode.EverythingInSelf )
                ?? throw new Exception( $"'{go.Name}' has no Terrain component - call terrain_get_info without an id to find the scene's terrain" );
        }
        else
        {
            // GetAllComponents skips disabled terrains, which would send the caller off to create a duplicate
            var all = scene.Components.GetAll<Terrain>( FindMode.EverythingInDescendants ).ToArray();
            terrain = all.Length switch
            {
                0 => throw new Exception( "The scene has no terrain - make one with terrain_create" ),
                1 => all[0],
                _ => throw new Exception( $"The scene has {all.Length} terrains - pass the id of one: {string.Join( ", ", all.Select( x => $"'{x.GameObject.Name}' {x.GameObject.Id}{(x.Active ? "" : " (disabled)")}" ) )}" )
            };
        }

        if ( terrain.Storage is null )
            throw new Exception( $"'{terrain.GameObject.Name}' has no terrain data - select it in the editor to give it some, or use terrain_create" );

        return terrain;
    }

    internal static float HeightOf( Terrain terrain, ushort raw ) => raw / (float)ushort.MaxValue * terrain.Storage.TerrainHeight;

    // Rounded, not truncated: float error puts some HeightOf round trips just under the raw value, and truncation would lower them a step
    internal static ushort RawOf( Terrain terrain, float height ) => (ushort)MathF.Round( Math.Clamp( height / terrain.Storage.TerrainHeight, 0f, 1f ) * ushort.MaxValue );

    /// <summary>The texel under a world position, through the terrain's transform. Null when it is off the terrain.</summary>
    internal static Vector2Int? TexelAt( Terrain terrain, Vector3 world )
    {
        var texel = UnclampedTexel( terrain, world );
        var res = terrain.Storage.Resolution;
        return texel.x < 0 || texel.y < 0 || texel.x >= res || texel.y >= res ? null : texel;
    }

    internal static Vector2Int RequireTexel( Terrain terrain, Vector3 world )
    {
        return TexelAt( terrain, world )
            ?? throw new Exception( $"{world} is off the terrain '{terrain.GameObject.Name}' - terrain_get_info shows its position and size" );
    }

    internal static TerrainBrush BrushAt( Terrain terrain, Vector3 world, float radius )
    {
        RequireFinite( "position and radius", world.x, world.y, world.z, radius );
        if ( radius <= 0 )
            throw new Exception( $"Radius must be above zero, got {radius}" );

        var storage = terrain.Storage;
        var res = storage.Resolution;
        var centre = UnclampedTexel( terrain, world );
        var texels = Math.Max( 1, (int)(radius / terrain.WorldScale.x / storage.TerrainSize * res) );

        int left = Math.Max( 0, centre.x - texels ), top = Math.Max( 0, centre.y - texels );
        int right = Math.Min( res, centre.x + texels + 1 ), bottom = Math.Min( res, centre.y + texels + 1 );

        if ( right <= left || bottom <= top )
            throw new Exception( $"A radius {radius} brush at {world} doesn't reach the terrain '{terrain.GameObject.Name}' - terrain_get_info shows its position and size" );

        return new TerrainBrush( centre, texels, new RectInt( left, top, right - left, bottom - top ), res );
    }

    static Vector2Int UnclampedTexel( Terrain terrain, Vector3 world )
    {
        var local = terrain.WorldTransform.PointToLocal( world );
        var scale = terrain.Storage.Resolution / terrain.Storage.TerrainSize;
        return new Vector2Int( (int)MathF.Floor( local.x * scale ), (int)MathF.Floor( local.y * scale ) );
    }

    /// <summary>
    /// Run an edit of one map and push it to rendering and collision, with undo. Mirrors the engine's
    /// own brush tools: the region is copied before and after, and undo or redo copies it back.
    /// </summary>
    internal static void Commit<T>( SceneEditorSession session, Terrain terrain, string undoName, Func<TerrainStorage, T[]> mapOf,
        Terrain.SyncFlags flags, RectInt region, Action edit ) where T : unmanaged
    {
        var before = Copy( mapOf( terrain.Storage ), terrain.Storage.Resolution, region );
        edit();
        var after = Copy( mapOf( terrain.Storage ), terrain.Storage.Resolution, region );

        terrain.ApplyStorageChanges( flags, region );

        // Resolved by id at undo time: undoing and redoing the terrain's creation replaces the component instance
        var scene = session.Scene;
        var componentId = terrain.Id;

        Action Restore( T[] data ) => () =>
        {
            if ( scene.Directory.FindComponentByGuid( componentId ) is not Terrain target || target.Storage is null )
                return;

            var map = mapOf( target.Storage );
            for ( var y = 0; y < region.Height; y++ )
                Array.Copy( data, y * region.Width, map, (region.Top + y) * target.Storage.Resolution + region.Left, region.Width );

            target.ApplyStorageChanges( flags, region );
        };

        session.AddUndo( undoName, Restore( before ), Restore( after ) );
        session.HasUnsavedChanges = true;
    }

    internal static void CommitHeights( SceneEditorSession session, Terrain terrain, string undoName, RectInt region, Action edit )
        => Commit( session, terrain, undoName, s => s.HeightMap, Terrain.SyncFlags.Height, region, edit );

    internal static void CommitControl( SceneEditorSession session, Terrain terrain, string undoName, RectInt region, Action edit )
        => Commit( session, terrain, undoName, s => s.ControlMap, Terrain.SyncFlags.Control, region, edit );

    static T[] Copy<T>( T[] map, int resolution, RectInt region ) where T : unmanaged
    {
        var copy = new T[region.Width * region.Height];
        for ( var y = 0; y < region.Height; y++ )
            Array.Copy( map, (region.Top + y) * resolution + region.Left, copy, y * region.Width, region.Width );
        return copy;
    }
}