Editor/MeshTools.cs

Editor MCP toolset that creates and inspects editable polygon meshes (MeshComponent). Builds box, plane, cylinder, wedge and arch meshes from explicit vertex and face lists, and the get-info tool reports faces, edges, vertices, materials, normals and bounds for other mesh edit tools.

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

namespace LevelTools;

[McpToolset( "mesh", "Editable polygon meshes (MeshComponent) in the scene - create blocks, planes, cylinders, wedges and arches, read their faces, edges and vertices, and edit them: extrude, clip, bevel, bridge, slice, materials, texture alignment and vertex colours" )]
public static class MeshTools
{
    /// <summary>
    /// Create a game object with a box-shaped MeshComponent centred on position, set up as the editor's
    /// block tool does (static, mesh collision, textures aligned to the grid). The user can undo this.
    /// Returns the new object's id - mesh_get_info lists its faces, edges and vertices for the edit tools.
    /// </summary>
    /// <param name="name">Name for the new object.</param>
    /// <param name="position">World position of the block's centre as 'x,y,z'.</param>
    /// <param name="size">Size along x, y and z as 'x,y,z'. Default 100,100,100.</param>
    /// <param name="material">Material asset path for every face, from asset_search type:vmat.</param>
    [McpTool( "mesh_create_block" )]
    public static object CreateBlock( string name = "Block", Vector3? position = null, Vector3? size = null, string material = DefaultMaterial )
    {
        var h = Half( size ?? new Vector3( 100 ) );

        Vector3[] vertices =
        [
            new( -h.x, -h.y, -h.z ), new( h.x, -h.y, -h.z ), new( h.x, h.y, -h.z ), new( -h.x, h.y, -h.z ),
            new( -h.x, -h.y, h.z ), new( h.x, -h.y, h.z ), new( h.x, h.y, h.z ), new( -h.x, h.y, h.z ),
        ];

        // Every face is wound counter-clockwise seen from outside
        int[][] faces = [[4, 5, 6, 7], [3, 2, 1, 0], [0, 1, 5, 4], [7, 6, 2, 3], [1, 2, 6, 5], [4, 7, 3, 0]];

        return Created( Create( name, position, material, vertices, faces ) );
    }

    /// <summary>
    /// Create a game object with a single flat, upward-facing quad MeshComponent centred on position. It
    /// has no thickness - mesh_thicken_faces gives it some. The user can undo this. Returns the new object's id.
    /// </summary>
    /// <param name="name">Name for the new object.</param>
    /// <param name="position">World position of the plane's centre as 'x,y,z'.</param>
    /// <param name="size">Size along x and y as 'x,y'. Default 100,100.</param>
    /// <param name="material">Material asset path, from asset_search type:vmat.</param>
    [McpTool( "mesh_create_plane" )]
    public static object CreatePlane( string name = "Plane", Vector3? position = null, Vector2? size = null, string material = DefaultMaterial )
    {
        var s = size ?? new Vector2( 100 );
        McpHelpers.RequirePositive( "size", new Vector3( s.x, s.y, 1 ) );
        float x = s.x / 2, y = s.y / 2;

        return Created( Create( name, position, material, [new( -x, -y, 0 ), new( x, -y, 0 ), new( x, y, 0 ), new( -x, y, 0 )], [[0, 1, 2, 3]] ) );
    }

    /// <summary>
    /// Create a game object with a capped cylinder MeshComponent standing along z and centred on position.
    /// Different x and y sizes make an elliptical cylinder. The user can undo this. Returns the new object's id.
    /// </summary>
    /// <param name="name">Name for the new object.</param>
    /// <param name="position">World position of the cylinder's centre as 'x,y,z'.</param>
    /// <param name="size">Diameter along x and y and height along z as 'x,y,z'. Default 100,100,100.</param>
    /// <param name="segments">Sides around the cylinder, 3 to 64.</param>
    /// <param name="material">Material asset path, from asset_search type:vmat.</param>
    [McpTool( "mesh_create_cylinder" )]
    public static object CreateCylinder( string name = "Cylinder", Vector3? position = null, Vector3? size = null,
        [Sandbox.Range( 3, 64 )] int segments = 16, string material = DefaultMaterial )
    {
        var h = Half( size ?? new Vector3( 100 ) );

        // Vertex 2i is on the bottom ring, 2i + 1 above it on the top ring
        var vertices = new List<Vector3>();
        for ( var i = 0; i < segments; i++ )
        {
            var angle = MathF.Tau * i / segments;
            var ring = new Vector3( MathF.Cos( angle ) * h.x, MathF.Sin( angle ) * h.y, 0 );
            vertices.Add( ring.WithZ( -h.z ) );
            vertices.Add( ring.WithZ( h.z ) );
        }

        var faces = new List<int[]>
        {
            Enumerable.Range( 0, segments ).Select( i => 2 * (segments - 1 - i) ).ToArray(),
            Enumerable.Range( 0, segments ).Select( i => 2 * i + 1 ).ToArray()
        };

        for ( var i = 0; i < segments; i++ )
        {
            var next = (i + 1) % segments;
            faces.Add( [2 * i, 2 * next, 2 * next + 1, 2 * i + 1] );
        }

        return Created( Create( name, position, material, vertices.ToArray(), faces.ToArray() ) );
    }

    /// <summary>
    /// Create a game object with a wedge MeshComponent centred on position: a triangular prism with a flat
    /// base and a ridge along y at the top, like a roof. The user can undo this. Returns the new object's id.
    /// </summary>
    /// <param name="name">Name for the new object.</param>
    /// <param name="position">World position of the wedge's centre as 'x,y,z'.</param>
    /// <param name="size">Base width along x, length along y and ridge height along z as 'x,y,z'. Default 100,100,100.</param>
    /// <param name="material">Material asset path, from asset_search type:vmat.</param>
    [McpTool( "mesh_create_wedge" )]
    public static object CreateWedge( string name = "Wedge", Vector3? position = null, Vector3? size = null, string material = DefaultMaterial )
    {
        var h = Half( size ?? new Vector3( 100 ) );

        Vector3[] vertices =
        [
            new( -h.x, -h.y, -h.z ), new( h.x, -h.y, -h.z ), new( h.x, h.y, -h.z ), new( -h.x, h.y, -h.z ),
            new( 0, -h.y, h.z ), new( 0, h.y, h.z ),
        ];

        return Created( Create( name, position, material, vertices, [[3, 2, 1, 0], [0, 1, 4], [5, 2, 3], [0, 4, 5, 3], [1, 2, 5, 4]] ) );
    }

    /// <summary>
    /// Create a game object with a closed arch MeshComponent: a half-ellipse band of the given thickness
    /// standing on the xy plane, open underneath, running through along y. Its base sits at position. The
    /// user can undo this. Returns the new object's id.
    /// </summary>
    /// <param name="name">Name for the new object.</param>
    /// <param name="position">World position of the middle of the arch's base as 'x,y,z'.</param>
    /// <param name="size">Outer width along x, depth along y and outer height along z as 'x,y,z'. Default 100,50,100.</param>
    /// <param name="thickness">Thickness of the band, less than half the width and less than the height.</param>
    /// <param name="segments">Segments around the curve, 3 to 32.</param>
    /// <param name="material">Material asset path, from asset_search type:vmat.</param>
    [McpTool( "mesh_create_arch" )]
    public static object CreateArch( string name = "Arch", Vector3? position = null, Vector3? size = null, float thickness = 20f,
        [Sandbox.Range( 3, 32 )] int segments = 8, string material = DefaultMaterial )
    {
        var s = size ?? new Vector3( 100, 50, 100 );
        McpHelpers.RequirePositive( "size", s );
        RequireFinite( "thickness", thickness );

        if ( thickness <= 0 || thickness >= s.x / 2 || thickness >= s.z )
            throw new Exception( $"Thickness {thickness} doesn't fit a {s.x} wide, {s.z} high arch - keep it above 0, under half the width and under the height" );

        float hx = s.x / 2, hy = s.y / 2;

        // Four vertices per step along the curve: outer front, outer back, inner front, inner back
        var vertices = new List<Vector3>();
        for ( var i = 0; i <= segments; i++ )
        {
            var angle = MathF.PI * i / segments;
            float c = -MathF.Cos( angle ), sin = MathF.Sin( angle );
            vertices.Add( new( c * hx, -hy, sin * s.z ) );
            vertices.Add( new( c * hx, hy, sin * s.z ) );
            vertices.Add( new( c * (hx - thickness), -hy, sin * (s.z - thickness) ) );
            vertices.Add( new( c * (hx - thickness), hy, sin * (s.z - thickness) ) );
        }

        var faces = new List<int[]>();
        for ( var i = 0; i < segments; i++ )
        {
            int a = 4 * i, b = 4 * (i + 1);
            faces.Add( [a, b, b + 1, a + 1] );
            faces.Add( [a + 2, a + 3, b + 3, b + 2] );
            faces.Add( [a, a + 2, b + 2, b] );
            faces.Add( [a + 1, b + 1, b + 3, a + 3] );
        }

        var end = 4 * segments;
        faces.Add( [0, 1, 3, 2] );
        faces.Add( [end, end + 2, end + 3, end + 1] );

        return Created( Create( name, position, material, vertices.ToArray(), faces.ToArray() ) );
    }

    /// <summary>
    /// A mesh's faces, edges and vertices with the indices the other mesh tools take, plus its collision
    /// type and local bounds. Positions, normals and bounds are in the object's local space, the space
    /// every mesh edit tool works in. An edge is listed by one of its two half-edge indices; either works.
    /// Indices can have gaps after faces or vertices are removed.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="limit">Most faces, edges and vertices to list of each kind. Default 100, max 1000. The counts are always complete.</param>
    [McpTool.ReadOnly( "mesh_get_info" )]
    public static object GetInfo( string id, [Sandbox.Range( 0, 1000 )] int limit = 100 )
    {
        var component = ForRead( id );
        var mesh = component.Mesh;
        var bounds = mesh.CalculateBounds();

        return new
        {
            Id = component.GameObject.Id,
            Name = component.GameObject.Name,
            Position = component.WorldPosition,
            component.Collision,
            Mesh = Counts( mesh ),
            Bounds = new { bounds.Mins, bounds.Maxs },
            Faces = mesh.FaceHandles.Take( limit ).Select( f =>
            {
                mesh.ComputeFaceNormal( f, out var normal );
                return new
                {
                    f.Index,
                    Material = mesh.GetFaceMaterial( f )?.ResourcePath,
                    Normal = normal,
                    Center = mesh.GetFaceCenter( f ),
                    Vertices = mesh.GetFaceVertices( f ).Select( v => v.Index ).ToArray()
                };
            } ).ToArray(),
            Edges = Edges( mesh ).Take( limit ).Select( e =>
            {
                mesh.GetEdgeVertices( e, out var a, out var b );
                return new { e.Index, Vertices = new[] { a.Index, b.Index }, Open = mesh.IsEdgeOpen( e ) };
            } ).ToArray(),
            Vertices = mesh.VertexHandles.Take( limit ).Select( v => new { v.Index, Position = mesh.GetVertexPosition( v ) } ).ToArray()
        };
    }

    static Vector3 Half( Vector3 size )
    {
        McpHelpers.RequirePositive( "size", size );
        return size / 2;
    }
}