Editor helper shared by the LevelTools MCP mesh tools. Resolves MeshComponents by GameObject id, runs mesh edits inside an undo scope and restores the undo and redo stacks when an edit throws or gets refused, creates new mesh objects, and converts integer face/vertex/edge indices into HalfEdgeMesh handles.
using System;
using System.Collections.Generic;
using System.Linq;
using Editor;
using HalfEdgeMesh;
using Sandbox;
using Sandbox.Helpers;
using static LevelTools.McpHelpers;
namespace LevelTools;
internal readonly record struct MeshCounts( int Faces, int Vertices, int Edges );
internal static class MeshEdit
{
internal const string DefaultMaterial = "materials/dev/reflectivity_30.vmat";
internal static MeshComponent ForRead( string id )
{
var go = FindByGuid( id );
var mesh = go.Components.Get<MeshComponent>( FindMode.EverythingInSelf )
?? throw new Exception( $"'{go.Name}' has no MeshComponent - the mesh_create tools make one" );
if ( mesh.Mesh is null )
throw new Exception( $"'{go.Name}' has a MeshComponent with no mesh in it - make one with the mesh_create tools" );
return mesh;
}
internal static (MeshComponent Mesh, SceneEditorSession Session) ForEdit( string id )
{
var mesh = ForRead( id );
// A disabled MeshComponent builds no model, so an edit could be neither seen nor collided with
if ( !mesh.Active )
throw new Exception( $"'{mesh.GameObject.Name}' is disabled - enable it with set_game_object before editing it" );
return (mesh, SessionOf( mesh.GameObject ));
}
/// <summary>
/// Run an edit with the component snapshot the engine's own mesh tools take, so undo and redo
/// restore the whole mesh and find the component by id themselves. When the edit throws or
/// succeeded says it failed, the entry this call recorded is restored and removed and the redo
/// history it cleared is put back, so the mesh and both undo stacks are as they were - only then
/// does this return or rethrow. If that can't be done (no entry was recorded, or restoring it
/// threw) it throws instead, saying the mesh may be partly changed. Refuse predictable failures
/// before calling this, so they never touch the undo history.
/// </summary>
internal static T Edit<T>( SceneEditorSession session, MeshComponent component, string undoName, Func<PolygonMesh, T> edit, Func<T, bool> succeeded = null )
{
var history = session.UndoSystem;
history.Back.TryPeek( out var before );
var redo = history.Forward.ToArray();
T result;
try
{
using var sceneScope = session.Scene.Push();
using var undoScope = session.UndoScope( undoName ).WithComponentChanges( component ).Push();
result = edit( component.Mesh );
component.RebuildMesh();
}
catch ( Exception e )
{
RollBack( history, before, redo, $"{undoName} failed ({e.Message})", e );
throw;
}
if ( succeeded?.Invoke( result ) == false )
RollBack( history, before, redo, $"{undoName} was refused", null );
return result;
}
static void RollBack( UndoSystem history, UndoSystem.Entry before, UndoSystem.Entry[] redo, string failure, Exception cause )
{
// When the scope's snapshot throws it records nothing, and the top entry is then the user's own
if ( !history.Back.TryPeek( out var failed ) || ReferenceEquals( failed, before ) )
throw new Exception( $"{failure} and recorded no undo entry to roll back with, so the mesh may be partly changed - check it with mesh_get_info", cause );
// Not UndoSystem.Undo(): it logs and swallows a failed restore, and would leave the failed edit on the redo stack
try
{
failed.Undo();
}
catch ( Exception e )
{
throw new Exception( $"{failure}, and rolling it back failed ({e.Message}), so the mesh may be partly changed - the edit stays on the undo stack; check the mesh with mesh_get_info", cause ?? e );
}
history.Back.Pop();
// Recording the failed edit cleared the redo history; with the mesh restored those entries apply again
history.Forward.Clear();
foreach ( var entry in redo.Reverse() )
history.Forward.Push( entry );
}
internal static MeshComponent Create( string name, Vector3? position, string material, Vector3[] vertices, int[][] faces )
{
if ( position is { } p )
RequireFinite( "position", p.x, p.y, p.z );
var session = ActiveSession();
var mat = LoadMaterial( material );
var mesh = new PolygonMesh();
var handles = mesh.AddVertices( vertices );
foreach ( var face in faces )
mesh.SetFaceMaterial( mesh.AddFace( face.Select( i => handles[i] ).ToArray() ), mat );
mesh.TextureAlignToGrid( Transform.Zero );
using var sceneScope = session.Scene.Push();
using var undoScope = session.UndoScope( $"Create {name}" ).WithGameObjectCreations().Push();
// The same setup as the editor's block tool (PrimitiveTool.Create)
var go = new GameObject( true, name );
go.WorldPosition = position ?? Vector3.Zero;
go.IsStatic = true;
var component = go.Components.Create<MeshComponent>( false );
component.Mesh = mesh;
component.SmoothingAngle = 40f;
component.Enabled = true;
return component;
}
internal static object Created( MeshComponent component )
{
return new { Id = component.GameObject.Id, Name = component.GameObject.Name, Position = component.WorldPosition, Mesh = Counts( component.Mesh ) };
}
// A missing path loads as the error material instead of failing, so check the file first
internal static Material LoadMaterial( string path )
{
if ( string.IsNullOrWhiteSpace( path ) || !Sandbox.FileSystem.Mounted.FileExists( path ) && !Sandbox.FileSystem.Mounted.FileExists( path + "_c" ) )
throw new Exception( $"No material '{path}' - find materials with asset_search type:vmat" );
return Material.Load( path );
}
/// <summary>One half-edge per edge, the lower index of the pair - the index get_info shows.</summary>
internal static IEnumerable<HalfEdgeHandle> Edges( PolygonMesh mesh ) => mesh.HalfEdgeHandles.Where( h => FullEdge( mesh, h ) == h );
/// <summary>The half-edge an edge is known by: the lower index of the pair, as the engine's own full-edge lookup picks.</summary>
internal static HalfEdgeHandle FullEdge( PolygonMesh mesh, HalfEdgeHandle h )
{
var opposite = mesh.GetOppositeHalfEdge( h );
return opposite.IsValid && opposite.Index < h.Index ? opposite : h;
}
internal static int[] Indices( IEnumerable<FaceHandle> faces ) => faces?.Where( f => f.IsValid ).Select( f => f.Index ).ToArray() ?? [];
internal static Exception Refused( string what ) =>
new( $"The engine couldn't {what}. The mesh is unchanged - check the indices with mesh_get_info" );
internal static MeshCounts Counts( PolygonMesh mesh ) => new( mesh.FaceHandles.Count(), mesh.VertexHandles.Count(), Edges( mesh ).Count() );
internal static FaceHandle[] Faces( PolygonMesh mesh, int[] indices ) => Handles( indices, "face", mesh.FaceHandleFromIndex, h => h.IsValid );
internal static FaceHandle[] FacesOrAll( PolygonMesh mesh, int[] indices ) => indices is { Length: > 0 } ? Faces( mesh, indices ) : mesh.FaceHandles.ToArray();
internal static VertexHandle[] Vertices( PolygonMesh mesh, int[] indices ) => Handles( indices, "vertex", mesh.VertexHandleFromIndex, h => h.IsValid );
// The engine matches its results against full edges, and would act twice on an edge given by both halves
internal static HalfEdgeHandle[] Edges( PolygonMesh mesh, int[] indices ) =>
Handles( indices, "edge", mesh.HalfEdgeHandleFromIndex, h => h.IsValid ).Select( h => FullEdge( mesh, h ) ).DistinctBy( h => h.Index ).ToArray();
// The mesh tool files import only MeshEdit statically, so they reach the shared check through here
internal static void RequireFinite( string name, params float[] values ) => McpHelpers.RequireFinite( name, values );
static T[] Handles<T>( int[] indices, string kind, Func<int, T> fromIndex, Func<T, bool> isValid )
{
if ( indices is null || indices.Length == 0 )
throw new Exception( $"Give at least one {kind} index - mesh_get_info lists them" );
return indices.Distinct().Select( i =>
{
var handle = i >= 0 ? fromIndex( i ) : default;
return i >= 0 && isValid( handle ) ? handle : throw new Exception( $"The mesh has no {kind} {i} - mesh_get_info lists its {kind} indices" );
} ).ToArray();
}
}