Editor MCP toolset named navmesh. Exposes tools to create NavMeshAgent, NavMeshArea and NavMeshLink objects, build the active scene's navmesh, generate and unload tiles, toggle deferred generation, read navmesh status, and query paths between two points. Mutating tools run inside undo scopes.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Editor;
using Editor.Mcp;
using Sandbox;
using Sandbox.Navigation;
using static LevelTools.McpHelpers;
namespace LevelTools;
[McpToolset( "navmesh", "AI navigation - build the scene's navmesh, place NavMeshAgent, NavMeshArea and NavMeshLink components, generate or unload tiles, and test paths" )]
public static class NavmeshTools
{
/// <summary>
/// Add a NavMeshAgent - to an existing game object when id is given, otherwise to a new one. Unset
/// properties keep the component defaults. The user can undo this. Returns the game object and
/// component ids.
/// </summary>
/// <param name="id">Game object id to add the agent to, from scene_tree or find_game_objects. Empty creates a new object.</param>
/// <param name="name">Name for the new object. Ignored when id is given.</param>
/// <param name="position">World position for the new object as 'x,y,z'. Ignored when id is given.</param>
/// <param name="height">Agent height in units.</param>
/// <param name="radius">Agent radius in units.</param>
/// <param name="speed">Maximum speed in units per second.</param>
/// <param name="acceleration">Maximum acceleration. Match or exceed speed for snappy movement.</param>
/// <param name="updatePosition">Whether the agent writes its simulated position back to the game object every frame.</param>
/// <param name="updateRotation">Whether the agent turns the game object to face its movement.</param>
[McpTool( "navmesh_create_agent" )]
public static object CreateAgent( string id = "", string name = "NavMesh Agent", Vector3? position = null,
float? height = null, float? radius = null, float? speed = null, float? acceleration = null,
bool? updatePosition = null, bool? updateRotation = null )
{
var at = position ?? Vector3.Zero;
RequireFinite( "position, height, radius, speed and acceleration", at.x, at.y, at.z, height ?? 0, radius ?? 0, speed ?? 0, acceleration ?? 0 );
var go = string.IsNullOrWhiteSpace( id ) ? null : FindByGuid( id );
var session = go is null ? ActiveSession() : SessionOf( go );
var undo = go is null
? session.UndoScope( "Create NavMesh Agent" ).WithGameObjectCreations()
: session.UndoScope( "Add NavMeshAgent" ).WithComponentCreations();
using var sceneScope = session.Scene.Push();
using var undoScope = undo.Push();
if ( go is null )
{
go = session.Scene.CreateObject();
go.Name = name;
if ( position is { } p ) go.WorldPosition = p;
}
var agent = go.Components.Create<NavMeshAgent>();
if ( height is { } h ) agent.Height = h;
if ( radius is { } r ) agent.Radius = r;
if ( speed is { } s ) agent.MaxSpeed = s;
if ( acceleration is { } a ) agent.Acceleration = a;
if ( updatePosition is { } up ) agent.UpdatePosition = up;
if ( updateRotation is { } ur ) agent.UpdateRotation = ur;
return new { Id = go.Id, ComponentId = agent.Id, Name = go.Name, Speed = agent.MaxSpeed, Radius = agent.Radius };
}
/// <summary>
/// Create a game object with a NavMeshArea - a box volume that blocks the navmesh (the default) or
/// marks it with an area definition. Run navmesh_generate afterwards to see the effect. The user
/// can undo this. Returns the new object's id.
/// </summary>
/// <param name="position">World position of the box centre as 'x,y,z'. Default origin.</param>
/// <param name="scale">World scale of the object as 'x,y,z'. The area's box is 100 units a side, so '2,2,1' covers 200x200x100.</param>
/// <param name="isBlocker">True stops navmesh generation inside the box entirely.</param>
/// <param name="name">Name for the new object.</param>
[McpTool( "navmesh_create_area" )]
public static object CreateArea( Vector3? position = null, Vector3? scale = null, bool isBlocker = true, string name = "NavMesh Area" )
{
Vector3 at = position ?? Vector3.Zero, size = scale ?? Vector3.One;
RequireFinite( "position and scale", at.x, at.y, at.z, size.x, size.y, size.z );
var session = ActiveSession();
using var sceneScope = session.Scene.Push();
using var undoScope = session.UndoScope( "Create NavMesh Area" ).WithGameObjectCreations().Push();
var go = session.Scene.CreateObject();
go.Name = name;
go.WorldPosition = position ?? Vector3.Zero;
if ( scale is { } sc ) go.WorldScale = sc;
var area = go.Components.Create<NavMeshArea>();
area.IsBlocker = isBlocker;
return new { Id = go.Id, Name = go.Name, Position = go.WorldPosition, IsBlocker = area.IsBlocker };
}
/// <summary>
/// Create a game object with a NavMeshLink - an off-mesh connection such as a jump, drop or ladder
/// between two points near the navmesh. The object sits at the midpoint. The user can undo this.
/// Returns the new object's id.
/// </summary>
/// <param name="start">Link start in world space as 'x,y,z'.</param>
/// <param name="end">Link end in world space as 'x,y,z'.</param>
/// <param name="bidirectional">Whether agents can traverse end to start too. Unset keeps the component default.</param>
/// <param name="name">Name for the new object.</param>
[McpTool( "navmesh_create_link" )]
public static object CreateLink( Vector3 start, Vector3 end, bool? bidirectional = null, string name = "NavMesh Link" )
{
RequireFinite( "start and end", start.x, start.y, start.z, end.x, end.y, end.z );
var session = ActiveSession();
var midpoint = (start + end) / 2f;
using var sceneScope = session.Scene.Push();
using var undoScope = session.UndoScope( "Create NavMesh Link" ).WithGameObjectCreations().Push();
var go = session.Scene.CreateObject();
go.Name = name;
go.WorldPosition = midpoint;
var link = go.Components.Create<NavMeshLink>();
link.LocalStartPosition = start - midpoint;
link.LocalEndPosition = end - midpoint;
if ( bidirectional is { } bd ) link.IsBiDirectional = bd;
return new { Id = go.Id, Name = go.Name, Position = go.WorldPosition, Start = start, End = end, Bidirectional = link.IsBiDirectional };
}
/// <summary>
/// Build the active scene's whole navmesh from its static and keyframed colliders and wait for it to
/// finish. Turns the scene's navmesh on if it was off and marks the scene unsaved, since that setting saves with it. Not
/// undoable; a rebuild replaces the previous mesh. Saving the scene in the editor bakes it to
/// navmesh/baked.navdata in the scene's folder, so it loads without rebuilding. Check the outcome
/// with navmesh_get_status or navmesh_query_path.
/// </summary>
[McpTool( "navmesh_generate" )]
public static async Task<object> Generate()
{
var session = ActiveSession();
var scene = session.Scene;
var navMesh = scene.NavMesh;
if ( navMesh.IsGenerating )
throw new Exception( "The navmesh is already generating - wait a moment and check navmesh_get_status" );
var timer = Stopwatch.StartNew();
var wasEnabled = navMesh.IsEnabled;
// Generate computes Bounds synchronously before its first await, so they are read here on the main thread
var generating = navMesh.Generate( scene.PhysicsWorld );
var bounds = navMesh.Bounds;
// IsEnabled saves with the scene, and only baking would otherwise mark it changed
if ( !wasEnabled && navMesh.IsEnabled )
session.HasUnsavedChanges = true;
// IsGenerating was refused above, so false here means a tile failed to build
if ( !await generating )
throw new Exception( "Some navmesh tiles failed to build - the rest were built; test the areas that matter with navmesh_query_path" );
return new
{
Generated = true,
GenerationTimeMs = timer.ElapsedMilliseconds,
Bounds = new { Mins = bounds.Mins, Maxs = bounds.Maxs }
};
}
/// <summary>
/// Queue navmesh tiles for rebuilding over the next frames - the tile at a position, or every tile
/// overlapping a box. For open worlds with deferred generation (navmesh_set_defer_generation). Returns
/// at once; not undoable. Needs the scene's navmesh on - navmesh_get_status shows IsEnabled.
/// </summary>
/// <param name="position">A world position inside the tile as 'x,y,z'. Used when the bounds are empty.</param>
/// <param name="boundsMin">Box minimum corner as 'x,y,z'. Give with boundsMax instead of position.</param>
/// <param name="boundsMax">Box maximum corner as 'x,y,z'. Give with boundsMin instead of position.</param>
[McpTool( "navmesh_generate_tile" )]
public static string GenerateTile( Vector3? position = null, Vector3? boundsMin = null, Vector3? boundsMax = null )
{
var navMesh = EnabledNavMesh();
if ( TileBounds( position, boundsMin, boundsMax ) is { } box )
{
navMesh.RequestTilesGeneration( box );
return $"Queued navmesh tiles overlapping {box.Mins} to {box.Maxs} for generation";
}
navMesh.RequestTileGeneration( position.Value );
return $"Queued the navmesh tile at {position.Value} for generation";
}
/// <summary>
/// Remove navmesh tiles - the tile at a position, or every tile overlapping a box - to free memory in
/// open worlds. Agents can no longer path there until navmesh_generate_tile rebuilds them. Not
/// undoable. Needs the scene's navmesh on.
/// </summary>
/// <param name="position">A world position inside the tile as 'x,y,z'. Used when the bounds are empty.</param>
/// <param name="boundsMin">Box minimum corner as 'x,y,z'. Give with boundsMax instead of position.</param>
/// <param name="boundsMax">Box maximum corner as 'x,y,z'. Give with boundsMin instead of position.</param>
[McpTool( "navmesh_unload_tile" )]
public static string UnloadTile( Vector3? position = null, Vector3? boundsMin = null, Vector3? boundsMax = null )
{
var navMesh = EnabledNavMesh();
if ( TileBounds( position, boundsMin, boundsMax ) is { } box )
{
navMesh.UnloadTiles( box );
return $"Unloaded navmesh tiles overlapping {box.Mins} to {box.Maxs}";
}
navMesh.UnloadTile( position.Value );
return $"Unloaded the navmesh tile at {position.Value}";
}
/// <summary>
/// Turn deferred navmesh generation on or off for the active scene. When on, loading the scene builds
/// no tiles and baked data is ignored - generate them on demand with navmesh_generate_tile. Saves with
/// the scene. The user can undo this.
/// </summary>
/// <param name="enabled">True to defer tile generation, false to build every tile on load.</param>
[McpTool( "navmesh_set_defer_generation" )]
public static string SetDeferGeneration( bool enabled = true )
{
var session = ActiveSession();
var navMesh = session.Scene.NavMesh;
var previous = navMesh.DeferGeneration;
navMesh.DeferGeneration = enabled;
session.AddUndo( "NavMesh Defer Generation", () => navMesh.DeferGeneration = previous, () => navMesh.DeferGeneration = enabled );
session.HasUnsavedChanges = true;
return enabled
? "Deferred generation on - tiles won't build on load; use navmesh_generate_tile"
: "Deferred generation off - every tile builds on load";
}
/// <summary>
/// The navigation state of the active scene - whether the navmesh is on, generating or dirty, deferred
/// generation, its agent settings and bounds, and the NavMeshAgent, NavMeshArea and NavMeshLink
/// counts, disabled components included. Lists the agents with their game object ids and whether each
/// is enabled.
/// </summary>
/// <param name="limit">How many agents to list. Default 100, max 1000. AgentCount is always the full count.</param>
[McpTool.ReadOnly( "navmesh_get_status" )]
public static object GetStatus( [Sandbox.Range( 0, 1000 )] int limit = 100 )
{
var scene = ReadScene();
var navMesh = scene.NavMesh;
var agents = scene.Components.GetAll<NavMeshAgent>( FindMode.EverythingInDescendants ).ToList();
return new
{
Scene = scene.Name,
IsEnabled = navMesh.IsEnabled,
IsGenerating = navMesh.IsGenerating,
IsDirty = navMesh.IsDirty,
DeferGeneration = navMesh.DeferGeneration,
AgentHeight = navMesh.AgentHeight,
AgentRadius = navMesh.AgentRadius,
AgentStepSize = navMesh.AgentStepSize,
AgentMaxSlope = navMesh.AgentMaxSlope,
Bounds = new { Mins = navMesh.Bounds.Mins, Maxs = navMesh.Bounds.Maxs },
AgentCount = agents.Count,
AreaCount = scene.Components.GetAll<NavMeshArea>( FindMode.EverythingInDescendants ).Count(),
LinkCount = scene.Components.GetAll<NavMeshLink>( FindMode.EverythingInDescendants ).Count(),
Agents = agents.Take( limit ).Select( a => new { Id = a.GameObject.Id, Name = a.GameObject.Name, Enabled = a.Active, Speed = a.MaxSpeed, Position = a.GameObject.WorldPosition } ).ToArray()
};
}
/// <summary>
/// Find a path across the active scene's navmesh between two points, as an agent would walk it. Both
/// points should be on or near walkable ground. Returns the waypoints, total distance and whether the
/// path is Complete or only Partial (ends at the closest reachable spot). Run navmesh_generate first.
/// </summary>
/// <param name="from">Path start as 'x,y,z'.</param>
/// <param name="to">Path end as 'x,y,z'.</param>
[McpTool.ReadOnly( "navmesh_query_path" )]
public static object QueryPath( Vector3 from, Vector3 to )
{
var navMesh = ReadScene().NavMesh;
if ( !navMesh.IsEnabled )
throw new Exception( "The scene's navmesh is off - build it with navmesh_generate first" );
var path = navMesh.CalculatePath( new CalculatePathRequest { Start = from, Target = to } );
if ( !path.IsValid )
{
throw new Exception( path.Status switch
{
NavMeshPathStatus.StartNotFound => $"No navmesh near the start {from} - pick a point on walkable ground, or rebuild with navmesh_generate",
NavMeshPathStatus.TargetNotFound => $"No navmesh near the target {to} - pick a point on walkable ground, or rebuild with navmesh_generate",
_ => $"No path between {from} and {to} ({path.Status}) - they may be on disconnected parts of the navmesh"
} );
}
var points = path.Points.Select( p => p.Position ).ToArray();
var distance = 0f;
for ( int i = 1; i < points.Length; i++ )
distance += points[i - 1].Distance( points[i] );
return new { Status = path.Status.ToString(), WaypointCount = points.Length, Distance = MathF.Round( distance, 1 ), Waypoints = points };
}
private static NavMesh EnabledNavMesh()
{
var navMesh = ActiveSession().Scene.NavMesh;
if ( !navMesh.IsEnabled )
throw new Exception( "The scene's navmesh is off, so tile calls would do nothing - turn it on with navmesh_generate or in the scene's NavMesh settings" );
return navMesh;
}
// Null means "use position"; throws when neither a full box nor a position was given
private static BBox? TileBounds( Vector3? position, Vector3? boundsMin, Vector3? boundsMax )
{
foreach ( var v in new[] { position, boundsMin, boundsMax } )
if ( v is { } given ) RequireFinite( "position and bounds", given.x, given.y, given.z );
if ( boundsMin is { } min && boundsMax is { } max )
return new BBox( min, max );
if ( boundsMin is not null || boundsMax is not null )
throw new Exception( "Give both boundsMin and boundsMax, or just position" );
if ( position is null )
throw new Exception( "Give position ('x,y,z'), or boundsMin and boundsMax, for the tiles" );
return null;
}
}