Editor/MeshEdgeTools.cs

Editor MCP toolset exposing half-edge mesh editing operations (bevel edges and vertices, split/dissolve/bridge/extend edges, connect vertices, move a vertex) as tools for an AI assistant. Each call goes through a shared undoable edit session and returns the new indices plus mesh counts.

using System;
using System.Collections.Generic;
using System.Linq;
using Editor.Mcp;
using HalfEdgeMesh;
using Sandbox;
using static LevelTools.MeshEdit;

namespace LevelTools;

[McpToolset( "mesh" )]
public static class MeshEdgeTools
{
    /// <summary>
    /// Round off edges: replace each with a band of faces cut distance back into its neighbours. More
    /// segments make a smoother curve; shape bends the band in or out. The user can undo this. Returns
    /// the new faces' indices.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="edges">Edge indices from mesh_get_info.</param>
    /// <param name="distance">How far back from each edge to cut, in units. The engine shortens a cut wider than the neighbouring faces.</param>
    /// <param name="segments">Faces across the bevel, 1 to 32.</param>
    /// <param name="shape">-1 to 1. 0 is a straight chamfer or round curve, positive bulges out, negative in.</param>
    [McpTool( "mesh_bevel_edges" )]
    public static object BevelEdges( string id, int[] edges, float distance = 5f, [Sandbox.Range( 1, 32 )] int segments = 1, [Sandbox.Range( -1, 1 )] float shape = 0f )
    {
        var (component, session) = ForEdit( id );
        var handles = Edges( component.Mesh, edges );

        RequireFinite( "distance and shape", distance, shape );
        if ( distance <= 0 )
            throw new Exception( "Distance must be above 0" );

        var added = new List<FaceHandle>();
        var ok = Edit( session, component, "Bevel Edges", mesh =>
        {
            // The same mode and UV follow-up as the editor's bevel: faces the bevel can't texture are aligned to the grid
            var needingUVs = new List<FaceHandle>();
            if ( !mesh.BevelEdges( handles, PolygonMesh.BevelEdgesMode.RemoveClosedEdges, segments, distance, shape, outNewFaces: added, outFacesNeedingUVs: needingUVs ) )
                return false;

            foreach ( var face in needingUVs )
                mesh.TextureAlignToGrid( mesh.Transform, face );

            mesh.ComputeFaceTextureParametersFromCoordinates( added );
            return true;
        }, ok => ok );

        if ( !ok )
            throw Refused( "bevel those edges" );

        return new { Id = component.GameObject.Id, Faces = Indices( added ), Mesh = Counts( component.Mesh ) };
    }

    /// <summary>
    /// Cut corners off: replace each vertex with a small face whose corners sit distance along each edge
    /// that met there. The user can undo this. Returns the new vertices' indices.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="vertices">Vertex indices from mesh_get_info.</param>
    /// <param name="distance">How far along each edge to cut, in units. Must stay under the shortest edge at those vertices, and under half of an edge whose both ends are listed.</param>
    [McpTool( "mesh_bevel_vertices" )]
    public static object BevelVertices( string id, int[] vertices, float distance = 5f )
    {
        var (component, session) = ForEdit( id );
        var handles = Vertices( component.Mesh, vertices );

        RequireFinite( "distance", distance );
        if ( distance <= 0 )
            throw new Exception( "Distance must be above 0" );

        // The engine never refuses a cut that reaches the next vertex, or the other end's cut when both ends
        // of an edge are bevelled; it collapses the corner into a degenerate mesh
        var mesh = component.Mesh;
        var limit = handles.Min( v =>
        {
            mesh.GetEdgesConnectedToVertex( v, out var connected );
            return connected.Min( e =>
            {
                mesh.GetEdgeVertices( e, out var a, out var b );
                var length = mesh.GetVertexPosition( a ).Distance( mesh.GetVertexPosition( b ) );
                return handles.Contains( a == v ? b : a ) ? length / 2 : length;
            } );
        } );

        if ( distance >= limit )
            throw new Exception( $"Distance {distance} reaches the next vertex, or the cut from the other end where both ends of an edge are bevelled - stay under {limit:0.##}" );

        var (ok, added) = Edit( session, component, "Bevel Vertices", mesh => (mesh.BevelVertices( handles, distance, out var outVertices ), outVertices), r => r.Item1 );
        if ( !ok )
            throw Refused( "bevel those vertices" );

        return new { Id = component.GameObject.Id, Vertices = added?.Select( v => v.Index ).ToArray() ?? [], Mesh = Counts( component.Mesh ) };
    }

    /// <summary>
    /// Cut the mesh open along edges: each edge becomes two open edges with vertices of their own, so the
    /// faces either side are no longer joined there. Nothing moves. The user can undo this. Returns the
    /// two new open edges of each one.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="edges">Edge indices from mesh_get_info.</param>
    [McpTool( "mesh_split_edges" )]
    public static object SplitEdges( string id, int[] edges )
    {
        var (component, session) = ForEdit( id );
        var handles = Edges( component.Mesh, edges );

        var (ok, a, b) = Edit( session, component, "Split Edges", mesh => (mesh.SplitEdges( handles, out var halvesA, out var halvesB ), halvesA, halvesB), r => r.Item1 );
        if ( !ok )
            throw Refused( "split those edges" );

        return new { Id = component.GameObject.Id, EdgesA = EdgeIndices( a ), EdgesB = EdgeIndices( b ), Mesh = Counts( component.Mesh ) };
    }

    /// <summary>
    /// Remove edges and merge the faces either side of each into one; vertices left in a straight line are
    /// removed too. mustBePlanar skips edges between faces that aren't flat with each other. The user can
    /// undo this. Face indices change - call mesh_get_info again before the next edit.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="edges">Edge indices from mesh_get_info.</param>
    /// <param name="mustBePlanar">Only dissolve edges whose two faces lie in one plane.</param>
    [McpTool( "mesh_dissolve_edges" )]
    public static object DissolveEdges( string id, int[] edges, bool mustBePlanar = false )
    {
        var (component, session) = ForEdit( id );
        var handles = Edges( component.Mesh, edges );
        var before = Counts( component.Mesh ).Edges;

        var removed = Edit( session, component, "Dissolve Edges", mesh =>
        {
            mesh.DissolveEdges( handles, mustBePlanar, PolygonMesh.DissolveRemoveVertexCondition.Colinear );
            mesh.ComputeFaceTextureCoordinatesFromParameters();
            return before - Counts( mesh ).Edges;
        }, removed => removed > 0 );

        if ( removed == 0 )
            throw new Exception( mustBePlanar ? "None of those edges lie between coplanar faces, so nothing was dissolved" : Refused( "dissolve those edges" ).Message );

        return new { Id = component.GameObject.Id, EdgesRemoved = removed, Mesh = Counts( component.Mesh ) };
    }

    /// <summary>
    /// Join two open edges (Open in mesh_get_info, e.g. the rims of holes) with a new face between them.
    /// The user can undo this. Returns the new face's index.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="edgeA">The first open edge's index.</param>
    /// <param name="edgeB">The second open edge's index.</param>
    [McpTool( "mesh_bridge_edges" )]
    public static object BridgeEdges( string id, int edgeA, int edgeB )
    {
        var (component, session) = ForEdit( id );
        var handles = Edges( component.Mesh, [edgeA, edgeB] );
        if ( handles.Length < 2 )
            throw new Exception( $"Edges {edgeA} and {edgeB} are the same edge - give two different open edges" );

        foreach ( var edge in handles )
        {
            if ( !component.Mesh.IsEdgeOpen( edge ) )
                throw new Exception( $"Edge {edge.Index} has faces on both sides - bridging needs two open edges, the ones mesh_get_info marks Open" );
        }

        var (ok, face) = Edit( session, component, "Bridge Edges", mesh => (mesh.BridgeEdges( handles[0], handles[1], out var newFace ), newFace), r => r.Item1 );
        if ( !ok )
            throw Refused( "bridge those edges - they must border different faces" );

        return new { Id = component.GameObject.Id, Face = face.Index, Mesh = Counts( component.Mesh ) };
    }

    /// <summary>
    /// Split a face by adding an edge between two of its vertices. Both vertices must be on the same face
    /// and the new edge must stay inside it. The user can undo this. Returns the new edge's index.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="vertexA">The first vertex's index.</param>
    /// <param name="vertexB">The second vertex's index.</param>
    [McpTool( "mesh_connect_vertices" )]
    public static object ConnectVertices( string id, int vertexA, int vertexB )
    {
        var (component, session) = ForEdit( id );
        var handles = Vertices( component.Mesh, [vertexA, vertexB] );
        if ( handles.Length < 2 )
            throw new Exception( "Give two different vertices" );

        var check = component.Mesh.CanConnectVertices( handles[0], handles[1] );
        if ( check != PolygonMesh.ConnectVerticesResult.Success )
        {
            throw new Exception( check switch
            {
                PolygonMesh.ConnectVerticesResult.AlreadyConnected => $"Vertices {vertexA} and {vertexB} already share an edge",
                PolygonMesh.ConnectVerticesResult.NoSharedFace => $"Vertices {vertexA} and {vertexB} aren't on the same face - mesh_get_info lists each face's vertices",
                PolygonMesh.ConnectVerticesResult.OutsideFace => "The edge would leave the face they share, which happens on concave faces - connect via another vertex",
                PolygonMesh.ConnectVerticesResult.BothVerticesInternal => "Both vertices are inside a face, not on its outline - at least one must be on the outline",
                _ => "Give two different vertices"
            } );
        }

        var (ok, edge) = Edit( session, component, "Connect Vertices", mesh => (mesh.ConnectVertices( handles[0], handles[1], out var newEdge ), newEdge), r => r.Item1 );
        if ( !ok )
            throw Refused( "connect those vertices" );

        return new { Id = component.GameObject.Id, Edge = edge.Index, Mesh = Counts( component.Mesh ) };
    }

    /// <summary>
    /// Grow new faces out of open edges, each extended amount units outward in the plane of its face - to
    /// widen a floor or continue a wall. The user can undo this. Returns the new faces and outer edges.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="edges">Open edge indices from mesh_get_info.</param>
    /// <param name="amount">How far to extend, in units.</param>
    [McpTool( "mesh_extend_edges" )]
    public static object ExtendEdges( string id, int[] edges, float amount )
    {
        var (component, session) = ForEdit( id );
        var handles = Edges( component.Mesh, edges );

        RequireFinite( "amount", amount );
        if ( amount == 0 )
            throw new Exception( "Give a non-zero amount" );

        if ( handles.FirstOrDefault( e => !component.Mesh.IsEdgeOpen( e ) ) is { IsValid: true } closed )
            throw new Exception( $"Edge {closed.Index} has faces on both sides - only open edges (Open in mesh_get_info) can be extended" );

        var (ok, newEdges, newFaces) = Edit( session, component, "Extend Edges", mesh => (mesh.ExtendEdges( handles, amount, out var outEdges, out var outFaces ), outEdges, outFaces), r => r.Item1 );
        if ( !ok )
            throw Refused( "extend those edges" );

        return new { Id = component.GameObject.Id, Edges = EdgeIndices( newEdges ), Faces = Indices( newFaces ), Mesh = Counts( component.Mesh ) };
    }

    /// <summary>
    /// Move one vertex to a new position in the object's local space; the faces using it follow. The user
    /// can undo this.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="vertex">The vertex's index from mesh_get_info.</param>
    /// <param name="position">New local position as 'x,y,z'.</param>
    [McpTool( "mesh_set_vertex_position" )]
    public static object SetVertexPosition( string id, int vertex, Vector3 position )
    {
        var (component, session) = ForEdit( id );
        var handle = Vertices( component.Mesh, [vertex] )[0];
        RequireFinite( "position", position.x, position.y, position.z );
        var previous = component.Mesh.GetVertexPosition( handle );

        Edit( session, component, "Move Vertex", mesh =>
        {
            mesh.SetVertexPosition( handle, position );

            // The texture stays put while the faces move, as with the editor's texture lock off (its default)
            mesh.ComputeFaceTextureCoordinatesFromParameters();
            return 0;
        } );

        return new { Id = component.GameObject.Id, Vertex = vertex, Previous = previous, Position = position };
    }

    static int[] EdgeIndices( IEnumerable<HalfEdgeHandle> edges ) => edges?.Where( e => e.IsValid ).Select( e => e.Index ).ToArray() ?? [];
}