{"TotalCount":14,"Files":[{"Ident":"arenula.leveltools","Path":"Editor/MeshSurfaceTools.cs","FileName":"MeshSurfaceTools.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":449884,"IsPrivate":false,"Code":"using System;\r\nusing System.Linq;\r\nusing Editor.Mcp;\r\nusing HalfEdgeMesh;\r\nusing Sandbox;\r\nusing static LevelTools.MeshEdit;\r\n\r\nnamespace LevelTools;\r\n\r\n[McpToolset( \u0022mesh\u0022 )]\r\npublic static class MeshSurfaceTools\r\n{\r\n    /// \u003Csummary\u003E\r\n    /// Paint faces with a material, recomputing their texture coordinates as the editor\u0027s material tool\r\n    /// does. The user can undo this.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022material\u0022\u003EMaterial asset path, from asset_search type:vmat.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022faces\u0022\u003EFace indices from mesh_get_info. Empty paints every face.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_set_face_material\u0022 )]\r\n    public static object SetFaceMaterial( string id, string material, int[] faces = null )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handles = FacesOrAll( component.Mesh, faces );\r\n        var mat = LoadMaterial( material );\r\n\r\n        Edit( session, component, \u0022Apply Material\u0022, mesh =\u003E\r\n        {\r\n            mesh.AssignMaterialToFaces( handles, mat );\r\n            return 0;\r\n        } );\r\n\r\n        return new { Id = component.GameObject.Id, Material = mat.ResourcePath, Faces = handles.Length };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Change how a texture is projected onto faces: the U and V axes it runs along (world space), its\r\n    /// offset in texels and its scale in units per texel. Only the arguments you give change; each face\r\n    /// keeps the rest of its own. The user can undo this. Returns each face\u0027s resulting parameters.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022faces\u0022\u003EFace indices from mesh_get_info. Empty changes every face.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022uAxis\u0022\u003EDirection the texture\u0027s U runs as \u0027x,y,z\u0027, e.g. \u00271,0,0\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022vAxis\u0022\u003EDirection the texture\u0027s V runs as \u0027x,y,z\u0027, e.g. \u00270,-1,0\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022offset\u0022\u003ETexture offset as \u0027u,v\u0027 in texels.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022scale\u0022\u003ETexture scale as \u0027u,v\u0027. The editor\u0027s default is 0.25,0.25.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_set_texture_params\u0022 )]\r\n    public static object SetTextureParams( string id, int[] faces = null, Vector3? uAxis = null, Vector3? vAxis = null, Vector2? offset = null, Vector2? scale = null )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handles = FacesOrAll( component.Mesh, faces );\r\n\r\n        if ( uAxis is null \u0026\u0026 vAxis is null \u0026\u0026 offset is null \u0026\u0026 scale is null )\r\n            throw new Exception( \u0022Give at least one of uAxis, vAxis, offset or scale\u0022 );\r\n\r\n        Vector3 ua = uAxis ?? default, va = vAxis ?? default;\r\n        Vector2 of = offset ?? default, sc = scale ?? default;\r\n        RequireFinite( \u0022uAxis, vAxis, offset and scale\u0022, ua.x, ua.y, ua.z, va.x, va.y, va.z, of.x, of.y, sc.x, sc.y );\r\n        if ( uAxis is { } u \u0026\u0026 u.IsNearlyZero() || vAxis is { } v \u0026\u0026 v.IsNearlyZero() || scale is { } s \u0026\u0026 (s.x == 0 || s.y == 0) )\r\n            throw new Exception( \u0022Axes and scale can\u0027t be zero\u0022 );\r\n\r\n        Edit( session, component, \u0022Set Texture Parameters\u0022, mesh =\u003E\r\n        {\r\n            foreach ( var face in handles )\r\n            {\r\n                mesh.GetFaceTextureParameters( face, out var axisU, out var axisV, out var faceScale );\r\n\r\n                // The engine keeps the offset in each axis\u0027 w component\r\n                var newU = new Vector4( uAxis ?? (Vector3)axisU, offset?.x ?? axisU.w );\r\n                var newV = new Vector4( vAxis ?? (Vector3)axisV, offset?.y ?? axisV.w );\r\n                mesh.SetFaceTextureParameters( face, newU, newV, scale ?? faceScale );\r\n            }\r\n\r\n            return 0;\r\n        } );\r\n\r\n        return new\r\n        {\r\n            Id = component.GameObject.Id,\r\n            Faces = handles.Select( face =\u003E\r\n            {\r\n                component.Mesh.GetFaceTextureParameters( face, out var axisU, out var axisV, out var faceScale );\r\n                return new { face.Index, UAxis = (Vector3)axisU, VAxis = (Vector3)axisV, Offset = new Vector2( axisU.w, axisV.w ), Scale = faceScale };\r\n            } ).ToArray()\r\n        };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Set the vertex colour of vertices, on every face corner that uses them. It shows only with a material\r\n    /// whose shader uses vertex colour. The user can undo this.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022vertices\u0022\u003EVertex indices from mesh_get_info.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022color\u0022\u003EColour as \u0027r,g,b,a\u0027 (0-1 floats), \u0027#rrggbb\u0027 or a name like \u0027red\u0027.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_set_vertex_color\u0022 )]\r\n    public static object SetVertexColor( string id, int[] vertices, string color )\r\n    {\r\n        var value = Color.Parse( color ) ?? throw new Exception( $\u0022\u0027{color}\u0027 isn\u0027t a colour - give \u0027r,g,b,a\u0027 as 0-1 floats, \u0027#rrggbb\u0027 or a name\u0022 );\r\n        return Paint( id, vertices, \u0022Set Vertex Color\u0022, ( mesh, corner ) =\u003E mesh.SetVertexColor( corner, value ) );\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Set the blend weights of vertices, on every face corner that uses them - what the editor\u0027s vertex\r\n    /// paint tool writes in Blend mode for materials that blend several layers. The user can undo this.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022vertices\u0022\u003EVertex indices from mesh_get_info.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022blend\u0022\u003EWeights as \u0027r,g,b,a\u0027, each 0 to 1.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_set_vertex_blend\u0022 )]\r\n    public static object SetVertexBlend( string id, int[] vertices, Vector4 blend )\r\n    {\r\n        RequireFinite( \u0022blend\u0022, blend.x, blend.y, blend.z, blend.w );\r\n        if ( new[] { blend.x, blend.y, blend.z, blend.w }.Any( x =\u003E x \u003C 0 || x \u003E 1 ) )\r\n            throw new Exception( \u0022Each blend weight must be 0 to 1\u0022 );\r\n\r\n        return Paint( id, vertices, \u0022Set Vertex Blend\u0022, ( mesh, corner ) =\u003E mesh.SetVertexBlend( corner, new Color( blend.x, blend.y, blend.z, blend.w ) ) );\r\n    }\r\n\r\n    static object Paint( string id, int[] vertices, string undoName, Action\u003CPolygonMesh, HalfEdgeHandle\u003E paint )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handles = Vertices( component.Mesh, vertices );\r\n\r\n        // Colour and blend live on face corners (half-edges), not vertices, so paint every corner a vertex has.\r\n        // The engine\u0027s list also holds the face-less half-edges of open boundaries, and is null for a lone vertex.\r\n        var mesh = component.Mesh;\r\n        var corners = handles.Select( v =\u003E mesh.GetFaceVerticesConnectedToVertex( v, out var all )\r\n            ? all.Where( c =\u003E mesh.GetHalfEdgeFace( c ).IsValid ).ToArray()\r\n            : [] ).ToArray();\r\n\r\n        if ( Array.FindIndex( corners, c =\u003E c.Length == 0 ) is var lone and \u003E= 0 )\r\n            throw new Exception( $\u0022Vertex {handles[lone].Index} is on no face, so it has no corners to paint\u0022 );\r\n\r\n        Edit( session, component, undoName, m =\u003E\r\n        {\r\n            foreach ( var corner in corners.SelectMany( c =\u003E c ) )\r\n                paint( m, corner );\r\n\r\n            return 0;\r\n        } );\r\n\r\n        return new { Id = component.GameObject.Id, Vertices = handles.Length, Corners = corners.Sum( c =\u003E c.Length ) };\r\n    }\r\n}\r\n"},{"Ident":"arenula.leveltools","Path":"Editor/MeshTools.cs","FileName":"MeshTools.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":449884,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing Editor.Mcp;\r\nusing Sandbox;\r\nusing static LevelTools.MeshEdit;\r\n\r\nnamespace LevelTools;\r\n\r\n[McpToolset( \u0022mesh\u0022, \u0022Editable 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\u0022 )]\r\npublic static class MeshTools\r\n{\r\n    /// \u003Csummary\u003E\r\n    /// Create a game object with a box-shaped MeshComponent centred on position, set up as the editor\u0027s\r\n    /// block tool does (static, mesh collision, textures aligned to the grid). The user can undo this.\r\n    /// Returns the new object\u0027s id - mesh_get_info lists its faces, edges and vertices for the edit tools.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022name\u0022\u003EName for the new object.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003EWorld position of the block\u0027s centre as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022size\u0022\u003ESize along x, y and z as \u0027x,y,z\u0027. Default 100,100,100.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022material\u0022\u003EMaterial asset path for every face, from asset_search type:vmat.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_create_block\u0022 )]\r\n    public static object CreateBlock( string name = \u0022Block\u0022, Vector3? position = null, Vector3? size = null, string material = DefaultMaterial )\r\n    {\r\n        var h = Half( size ?? new Vector3( 100 ) );\r\n\r\n        Vector3[] vertices =\r\n        [\r\n            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 ),\r\n            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 ),\r\n        ];\r\n\r\n        // Every face is wound counter-clockwise seen from outside\r\n        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]];\r\n\r\n        return Created( Create( name, position, material, vertices, faces ) );\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Create a game object with a single flat, upward-facing quad MeshComponent centred on position. It\r\n    /// has no thickness - mesh_thicken_faces gives it some. The user can undo this. Returns the new object\u0027s id.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022name\u0022\u003EName for the new object.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003EWorld position of the plane\u0027s centre as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022size\u0022\u003ESize along x and y as \u0027x,y\u0027. Default 100,100.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022material\u0022\u003EMaterial asset path, from asset_search type:vmat.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_create_plane\u0022 )]\r\n    public static object CreatePlane( string name = \u0022Plane\u0022, Vector3? position = null, Vector2? size = null, string material = DefaultMaterial )\r\n    {\r\n        var s = size ?? new Vector2( 100 );\r\n        McpHelpers.RequirePositive( \u0022size\u0022, new Vector3( s.x, s.y, 1 ) );\r\n        float x = s.x / 2, y = s.y / 2;\r\n\r\n        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]] ) );\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Create a game object with a capped cylinder MeshComponent standing along z and centred on position.\r\n    /// Different x and y sizes make an elliptical cylinder. The user can undo this. Returns the new object\u0027s id.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022name\u0022\u003EName for the new object.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003EWorld position of the cylinder\u0027s centre as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022size\u0022\u003EDiameter along x and y and height along z as \u0027x,y,z\u0027. Default 100,100,100.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022segments\u0022\u003ESides around the cylinder, 3 to 64.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022material\u0022\u003EMaterial asset path, from asset_search type:vmat.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_create_cylinder\u0022 )]\r\n    public static object CreateCylinder( string name = \u0022Cylinder\u0022, Vector3? position = null, Vector3? size = null,\r\n        [Sandbox.Range( 3, 64 )] int segments = 16, string material = DefaultMaterial )\r\n    {\r\n        var h = Half( size ?? new Vector3( 100 ) );\r\n\r\n        // Vertex 2i is on the bottom ring, 2i \u002B 1 above it on the top ring\r\n        var vertices = new List\u003CVector3\u003E();\r\n        for ( var i = 0; i \u003C segments; i\u002B\u002B )\r\n        {\r\n            var angle = MathF.Tau * i / segments;\r\n            var ring = new Vector3( MathF.Cos( angle ) * h.x, MathF.Sin( angle ) * h.y, 0 );\r\n            vertices.Add( ring.WithZ( -h.z ) );\r\n            vertices.Add( ring.WithZ( h.z ) );\r\n        }\r\n\r\n        var faces = new List\u003Cint[]\u003E\r\n        {\r\n            Enumerable.Range( 0, segments ).Select( i =\u003E 2 * (segments - 1 - i) ).ToArray(),\r\n            Enumerable.Range( 0, segments ).Select( i =\u003E 2 * i \u002B 1 ).ToArray()\r\n        };\r\n\r\n        for ( var i = 0; i \u003C segments; i\u002B\u002B )\r\n        {\r\n            var next = (i \u002B 1) % segments;\r\n            faces.Add( [2 * i, 2 * next, 2 * next \u002B 1, 2 * i \u002B 1] );\r\n        }\r\n\r\n        return Created( Create( name, position, material, vertices.ToArray(), faces.ToArray() ) );\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Create a game object with a wedge MeshComponent centred on position: a triangular prism with a flat\r\n    /// base and a ridge along y at the top, like a roof. The user can undo this. Returns the new object\u0027s id.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022name\u0022\u003EName for the new object.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003EWorld position of the wedge\u0027s centre as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022size\u0022\u003EBase width along x, length along y and ridge height along z as \u0027x,y,z\u0027. Default 100,100,100.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022material\u0022\u003EMaterial asset path, from asset_search type:vmat.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_create_wedge\u0022 )]\r\n    public static object CreateWedge( string name = \u0022Wedge\u0022, Vector3? position = null, Vector3? size = null, string material = DefaultMaterial )\r\n    {\r\n        var h = Half( size ?? new Vector3( 100 ) );\r\n\r\n        Vector3[] vertices =\r\n        [\r\n            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 ),\r\n            new( 0, -h.y, h.z ), new( 0, h.y, h.z ),\r\n        ];\r\n\r\n        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]] ) );\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Create a game object with a closed arch MeshComponent: a half-ellipse band of the given thickness\r\n    /// standing on the xy plane, open underneath, running through along y. Its base sits at position. The\r\n    /// user can undo this. Returns the new object\u0027s id.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022name\u0022\u003EName for the new object.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003EWorld position of the middle of the arch\u0027s base as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022size\u0022\u003EOuter width along x, depth along y and outer height along z as \u0027x,y,z\u0027. Default 100,50,100.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022thickness\u0022\u003EThickness of the band, less than half the width and less than the height.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022segments\u0022\u003ESegments around the curve, 3 to 32.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022material\u0022\u003EMaterial asset path, from asset_search type:vmat.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_create_arch\u0022 )]\r\n    public static object CreateArch( string name = \u0022Arch\u0022, Vector3? position = null, Vector3? size = null, float thickness = 20f,\r\n        [Sandbox.Range( 3, 32 )] int segments = 8, string material = DefaultMaterial )\r\n    {\r\n        var s = size ?? new Vector3( 100, 50, 100 );\r\n        McpHelpers.RequirePositive( \u0022size\u0022, s );\r\n        RequireFinite( \u0022thickness\u0022, thickness );\r\n\r\n        if ( thickness \u003C= 0 || thickness \u003E= s.x / 2 || thickness \u003E= s.z )\r\n            throw new Exception( $\u0022Thickness {thickness} doesn\u0027t fit a {s.x} wide, {s.z} high arch - keep it above 0, under half the width and under the height\u0022 );\r\n\r\n        float hx = s.x / 2, hy = s.y / 2;\r\n\r\n        // Four vertices per step along the curve: outer front, outer back, inner front, inner back\r\n        var vertices = new List\u003CVector3\u003E();\r\n        for ( var i = 0; i \u003C= segments; i\u002B\u002B )\r\n        {\r\n            var angle = MathF.PI * i / segments;\r\n            float c = -MathF.Cos( angle ), sin = MathF.Sin( angle );\r\n            vertices.Add( new( c * hx, -hy, sin * s.z ) );\r\n            vertices.Add( new( c * hx, hy, sin * s.z ) );\r\n            vertices.Add( new( c * (hx - thickness), -hy, sin * (s.z - thickness) ) );\r\n            vertices.Add( new( c * (hx - thickness), hy, sin * (s.z - thickness) ) );\r\n        }\r\n\r\n        var faces = new List\u003Cint[]\u003E();\r\n        for ( var i = 0; i \u003C segments; i\u002B\u002B )\r\n        {\r\n            int a = 4 * i, b = 4 * (i \u002B 1);\r\n            faces.Add( [a, b, b \u002B 1, a \u002B 1] );\r\n            faces.Add( [a \u002B 2, a \u002B 3, b \u002B 3, b \u002B 2] );\r\n            faces.Add( [a, a \u002B 2, b \u002B 2, b] );\r\n            faces.Add( [a \u002B 1, b \u002B 1, b \u002B 3, a \u002B 3] );\r\n        }\r\n\r\n        var end = 4 * segments;\r\n        faces.Add( [0, 1, 3, 2] );\r\n        faces.Add( [end, end \u002B 2, end \u002B 3, end \u002B 1] );\r\n\r\n        return Created( Create( name, position, material, vertices.ToArray(), faces.ToArray() ) );\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// A mesh\u0027s faces, edges and vertices with the indices the other mesh tools take, plus its collision\r\n    /// type and local bounds. Positions, normals and bounds are in the object\u0027s local space, the space\r\n    /// every mesh edit tool works in. An edge is listed by one of its two half-edge indices; either works.\r\n    /// Indices can have gaps after faces or vertices are removed.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022limit\u0022\u003EMost faces, edges and vertices to list of each kind. Default 100, max 1000. The counts are always complete.\u003C/param\u003E\r\n    [McpTool.ReadOnly( \u0022mesh_get_info\u0022 )]\r\n    public static object GetInfo( string id, [Sandbox.Range( 0, 1000 )] int limit = 100 )\r\n    {\r\n        var component = ForRead( id );\r\n        var mesh = component.Mesh;\r\n        var bounds = mesh.CalculateBounds();\r\n\r\n        return new\r\n        {\r\n            Id = component.GameObject.Id,\r\n            Name = component.GameObject.Name,\r\n            Position = component.WorldPosition,\r\n            component.Collision,\r\n            Mesh = Counts( mesh ),\r\n            Bounds = new { bounds.Mins, bounds.Maxs },\r\n            Faces = mesh.FaceHandles.Take( limit ).Select( f =\u003E\r\n            {\r\n                mesh.ComputeFaceNormal( f, out var normal );\r\n                return new\r\n                {\r\n                    f.Index,\r\n                    Material = mesh.GetFaceMaterial( f )?.ResourcePath,\r\n                    Normal = normal,\r\n                    Center = mesh.GetFaceCenter( f ),\r\n                    Vertices = mesh.GetFaceVertices( f ).Select( v =\u003E v.Index ).ToArray()\r\n                };\r\n            } ).ToArray(),\r\n            Edges = Edges( mesh ).Take( limit ).Select( e =\u003E\r\n            {\r\n                mesh.GetEdgeVertices( e, out var a, out var b );\r\n                return new { e.Index, Vertices = new[] { a.Index, b.Index }, Open = mesh.IsEdgeOpen( e ) };\r\n            } ).ToArray(),\r\n            Vertices = mesh.VertexHandles.Take( limit ).Select( v =\u003E new { v.Index, Position = mesh.GetVertexPosition( v ) } ).ToArray()\r\n        };\r\n    }\r\n\r\n    static Vector3 Half( Vector3 size )\r\n    {\r\n        McpHelpers.RequirePositive( \u0022size\u0022, size );\r\n        return size / 2;\r\n    }\r\n}\r\n"},{"Ident":"arenula.leveltools","Path":"Editor/PrefabTools.cs","FileName":"PrefabTools.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":449884,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing Editor;\r\nusing Editor.Mcp;\r\nusing Sandbox;\r\nusing static LevelTools.McpHelpers;\r\n\r\nnamespace LevelTools;\r\n\r\n[McpToolset( \u0022prefab\u0022, \u0022Prefab files and their instances - make a prefab from an object, find instances, see per-property overrides, and apply, revert or unlink an instance\u0022 )]\r\npublic static class PrefabTools\r\n{\r\n    /// \u003Csummary\u003E\r\n    /// Save a game object and its children as a new prefab file, and turn the object into an instance\r\n    /// of it. When the object is already part of a prefab instance, the engine replaces it with a\r\n    /// linked clone, so the returned Id differs from the one given. The file is written immediately;\r\n    /// the user can undo the change to the scene, but not the file.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id, from scene_tree or find_game_objects.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022path\u0022\u003ENew prefab path relative to Assets, e.g. \u0027prefabs/crate.prefab\u0027. Missing folders are created.\u003C/param\u003E\r\n    [McpTool( \u0022prefab_create\u0022 )]\r\n    public static object Create( string id, string path )\r\n    {\r\n        var go = FindByGuid( id );\r\n        var full = AssetsPath( path );\r\n\r\n        if ( File.Exists( full ) )\r\n            throw new Exception( $\u0022\u0027{path}\u0027 already exists - use prefab_apply to update an existing prefab, or pick a new path\u0022 );\r\n\r\n        var session = SessionOf( go );\r\n        var before = new { Id = go.Id, WasInstanceOf = go.IsPrefabInstance ? OutermostRoot( go ).PrefabInstanceSource : null };\r\n\r\n        Directory.CreateDirectory( Path.GetDirectoryName( full ) );\r\n\r\n        using var sceneScope = session.Scene.Push();\r\n        GameObject result;\r\n        var undo = session.UndoScope( \u0022Convert to Prefab\u0022 ).WithGameObjectChanges( go, GameObjectUndoFlags.All ).WithGameObjectCreations();\r\n\r\n        // An instance is replaced by a clone and destroyed; without recording that, undo removes the clone and loses the object\r\n        if ( go.IsPrefabInstance )\r\n            undo = undo.WithGameObjectDestructions( go );\r\n\r\n        using ( undo.Push() )\r\n        {\r\n            result = EditorUtility.Prefabs.ConvertGameObjectToPrefab( go, full );\r\n        }\r\n\r\n        if ( result is null )\r\n            throw new Exception( $\u0022The engine couldn\u0027t write \u0027{path}\u0027 - a prefab can\u0027t contain an instance of itself; read_console has the reason\u0022 );\r\n\r\n        return new { Id = result.Id, Path = result.PrefabInstanceSource, Before = before, After = new { IsInstance = result.IsPrefabInstance } };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// List the prefab instances in the open scene - outermost instances only, so a prefab nested inside\r\n    /// another instance is not counted. Returns each instance\u0027s id, prefab and whether it has overrides.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022path\u0022\u003EOnly instances of this prefab, relative to Assets, e.g. \u0027prefabs/crate.prefab\u0027. Empty lists every instance.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022limit\u0022\u003EHow many instances to return. Default 50, max 1000. Total is always the full count.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022offset\u0022\u003EHow many instances to skip, for paging.\u003C/param\u003E\r\n    [McpTool.ReadOnly( \u0022prefab_get_instances\u0022 )]\r\n    public static object GetInstances( string path = \u0022\u0022, [Sandbox.Range( 0, 1000 )] int limit = 50, [Sandbox.Range( 0, int.MaxValue )] int offset = 0 )\r\n    {\r\n        var want = NormalizePrefabPath( path );\r\n\r\n        var all = ReadScene().GetAllObjects( false )\r\n            .Where( x =\u003E EditorUtility.Prefabs.IsOuterMostPrefabRoot( x ) )\r\n            .Where( x =\u003E want.Length == 0 || string.Equals( NormalizePrefabPath( x.PrefabInstanceSource ), want, StringComparison.OrdinalIgnoreCase ) )\r\n            .ToList();\r\n\r\n        var page = all.Skip( offset ).Take( limit ).Select( x =\u003E new\r\n        {\r\n            x.Id,\r\n            x.Name,\r\n            Prefab = x.PrefabInstanceSource,\r\n            Position = x.WorldPosition,\r\n            IsModified = EditorUtility.Prefabs.IsInstanceModified( x ),\r\n        } ).ToList();\r\n\r\n        return new { Total = all.Count, Showing = page.Count, Instances = page };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Show how a prefab instance differs from its prefab: the properties overridden on each object and\r\n    /// component, and the objects and components added to the instance. Give any object in the instance;\r\n    /// the report covers the whole outermost instance. Position, rotation, scale and name on the instance\r\n    /// root are not counted, as in the inspector.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EId of any game object in the instance, from scene_tree or prefab_get_instances.\u003C/param\u003E\r\n    [McpTool.ReadOnly( \u0022prefab_get_overrides\u0022 )]\r\n    public static object GetOverrides( string id )\r\n    {\r\n        return Overrides( FindByGuid( id ) );\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Write an instance\u0027s overrides back into its prefab file, so every instance picks them up. On the\r\n    /// outermost root the whole instance is written; on an object inside it, only that part; on an object\r\n    /// added to the instance (prefab_get_overrides lists them), it is added to the prefab with its children. The file\r\n    /// is written immediately and the user cannot undo it; the scene is flagged unsaved, as the editor\u0027s own\r\n    /// Apply does. Returns the overrides before and after.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EId of the instance root, or of a nested prefab instance inside it.\u003C/param\u003E\r\n    [McpTool( \u0022prefab_apply\u0022 )]\r\n    public static object Apply( string id )\r\n    {\r\n        var go = FindByGuid( id );\r\n        var root = OutermostRoot( go );\r\n        var session = SessionOf( go );\r\n        var before = Overrides( go );\r\n\r\n        // An added object has no counterpart in the prefab for ApplyGameObjectInstanceChangesToPrefab to\r\n        // update (it throws on null), so it is added instead, as the editor\u0027s menu does\r\n        GameObject added = null;\r\n        for ( var x = go; x != root; x = x.Parent )\r\n        {\r\n            if ( EditorUtility.Prefabs.IsGameObjectAddedToInstance( x ) ) added = x;\r\n        }\r\n\r\n        if ( added is not null \u0026\u0026 added != go )\r\n            throw new Exception( $\u0022{go.Id} is inside {added.Id}, which was added to the instance - apply {added.Id} to add it to the prefab with its children\u0022 );\r\n\r\n        using var sceneScope = session.Scene.Push();\r\n\r\n        if ( go == root )\r\n            EditorUtility.Prefabs.WriteInstanceToPrefab( go );\r\n        else if ( added == go )\r\n            EditorUtility.Prefabs.AddInstanceAddedGameObjectToPrefab( go );\r\n        else\r\n            EditorUtility.Prefabs.ApplyGameObjectInstanceChangesToPrefab( go );\r\n\r\n        session.HasUnsavedChanges = true;\r\n\r\n        return new { Before = before, After = Overrides( FindByGuid( id ) ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Throw away an instance\u0027s overrides on this object and everything under it, so it matches its prefab\r\n    /// again. The user can undo this. Returns the overrides before and after.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EId of any game object in the instance; the revert covers it and its children.\u003C/param\u003E\r\n    [McpTool( \u0022prefab_revert\u0022 )]\r\n    public static object Revert( string id )\r\n    {\r\n        var go = FindByGuid( id );\r\n        var session = SessionOf( go );\r\n        var before = Overrides( go );\r\n\r\n        using var sceneScope = session.Scene.Push();\r\n        // Properties alone snapshots only the object\u0027s own fields: a component-only revert would record no undo\r\n        // step (the editor\u0027s own Revert menu has this bug), so capture components and children too\r\n        using ( session.UndoScope( \u0022Revert Changes\u0022 ).WithGameObjectChanges( go, GameObjectUndoFlags.All ).Push() )\r\n        {\r\n            EditorUtility.Prefabs.RevertGameObjectInstanceChanges( go );\r\n        }\r\n\r\n        return new { Before = before, After = Overrides( FindByGuid( id ) ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Unlink a prefab instance so it becomes ordinary game objects; prefabs nested inside it stay linked.\r\n    /// Only the outermost instance root can be unlinked. The user can undo this.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EId of the outermost instance root, from prefab_get_instances.\u003C/param\u003E\r\n    [McpTool( \u0022prefab_break\u0022 )]\r\n    public static object Break( string id )\r\n    {\r\n        var go = FindByGuid( id );\r\n        var root = OutermostRoot( go );\r\n\r\n        // BreakFromPrefab does nothing, silently, on anything but the outermost root\r\n        if ( root != go )\r\n            throw new Exception( $\u0022{go.Id} is inside the instance rooted at {root.Id} - unlink the outermost instance {root.Id}\u0022 );\r\n\r\n        var session = SessionOf( go );\r\n        var before = new { Prefab = go.PrefabInstanceSource };\r\n\r\n        using var sceneScope = session.Scene.Push();\r\n        using ( session.UndoScope( \u0022Unlink From Prefab\u0022 ).WithGameObjectChanges( go, GameObjectUndoFlags.All ).Push() )\r\n        {\r\n            go.BreakFromPrefab();\r\n        }\r\n\r\n        return new { Id = go.Id, Before = before, After = new { IsInstance = go.IsPrefabInstance } };\r\n    }\r\n\r\n    static object Overrides( GameObject go )\r\n    {\r\n        var root = OutermostRoot( go );\r\n        var overrides = new List\u003Cobject\u003E();\r\n        var addedObjects = new List\u003Cobject\u003E();\r\n        var addedComponents = new List\u003Cobject\u003E();\r\n\r\n        foreach ( var obj in root.GetAllObjects( false ) )\r\n        {\r\n            // An instance placed inside another instance counts as added to that one, not to itself\r\n            if ( obj != root \u0026\u0026 EditorUtility.Prefabs.IsGameObjectAddedToInstance( obj ) )\r\n            {\r\n                addedObjects.Add( new { obj.Id, obj.Name } );\r\n                continue;\r\n            }\r\n\r\n            if ( !EditorUtility.Prefabs.IsGameObjectInstanceModified( obj ) ) continue;\r\n\r\n            // Position, rotation and scale are serialized on the transform, the rest on the object\r\n            var own = OverriddenProperties( obj.GetSerialized() ).Concat( OverriddenProperties( obj.Transform.GetSerialized() ) ).Distinct().ToList();\r\n            if ( own.Count \u003E 0 )\r\n                overrides.Add( new { GameObjectId = obj.Id, Target = \u0022GameObject\u0022, ComponentId = (Guid?)null, Properties = own } );\r\n\r\n            foreach ( var comp in obj.Components.GetAll() )\r\n            {\r\n                if ( EditorUtility.Prefabs.IsComponentAddedToInstance( comp ) )\r\n                {\r\n                    addedComponents.Add( new { GameObjectId = obj.Id, ComponentId = comp.Id, Type = comp.GetType().Name } );\r\n                    continue;\r\n                }\r\n\r\n                if ( !EditorUtility.Prefabs.IsComponentInstanceModified( comp ) ) continue;\r\n\r\n                var props = OverriddenProperties( comp.GetSerialized() ).ToList();\r\n                if ( props.Count \u003E 0 )\r\n                    overrides.Add( new { GameObjectId = obj.Id, Target = comp.GetType().Name, ComponentId = (Guid?)comp.Id, Properties = props } );\r\n            }\r\n        }\r\n\r\n        return new\r\n        {\r\n            Id = root.Id,\r\n            Prefab = root.PrefabInstanceSource,\r\n            IsModified = EditorUtility.Prefabs.IsInstanceModified( root ),\r\n            Overrides = overrides,\r\n            AddedObjects = addedObjects,\r\n            AddedComponents = addedComponents,\r\n        };\r\n    }\r\n\r\n    static IEnumerable\u003Cstring\u003E OverriddenProperties( SerializedObject so )\r\n    {\r\n        return so.Where( EditorUtility.Prefabs.IsPropertyOverridden ).Select( p =\u003E p.Name );\r\n    }\r\n\r\n    // OutermostPrefabInstanceRoot is internal, so walk up to the root the public check recognises\r\n    static GameObject OutermostRoot( GameObject go )\r\n    {\r\n        for ( var x = go; x is not null; x = x.Parent )\r\n        {\r\n            if ( EditorUtility.Prefabs.IsOuterMostPrefabRoot( x ) ) return x;\r\n        }\r\n\r\n        throw new Exception( $\u0022{go.Id} isn\u0027t part of a prefab instance - prefab_get_instances lists the instances in the scene\u0022 );\r\n    }\r\n\r\n    static string NormalizePrefabPath( string path )\r\n    {\r\n        return (path ?? \u0022\u0022).Replace( \u0027\\\\\u0027, \u0027/\u0027 ).TrimStart( \u0027/\u0027 );\r\n    }\r\n}\r\n"},{"Ident":"arenula.leveltools","Path":"Editor/McpHelpers.cs","FileName":"McpHelpers.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":449884,"IsPrivate":false,"Code":"using System;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing Editor;\r\nusing Sandbox;\r\n\r\nnamespace LevelTools;\r\n\r\n// The first-party tools keep equivalents of these private to their own classes, so this library carries its own copy\r\ninternal static class McpHelpers\r\n{\r\n    internal static SceneEditorSession ActiveSession()\r\n    {\r\n        return SceneEditorSession.Active ?? throw new Exception( \u0022No scene is open in the editor\u0022 );\r\n    }\r\n\r\n    // Undo and unsaved changes belong to the session that owns the object, not whichever tab is active\r\n    internal static SceneEditorSession SessionOf( GameObject go )\r\n    {\r\n        return go.Scene?.Editor as SceneEditorSession ?? ActiveSession();\r\n    }\r\n\r\n    // Read-only tools also work on the running game\u0027s scene when no editor session is active\r\n    internal static Scene ReadScene()\r\n    {\r\n        return SceneEditorSession.Active?.Scene ?? Game.ActiveScene ?? throw new Exception( \u0022No scene is open in the editor\u0022 );\r\n    }\r\n\r\n    // Active session first, so an id shared by duplicated scenes means the object in the tab being looked at\r\n    internal static GameObject FindByGuid( string id )\r\n    {\r\n        if ( !Guid.TryParse( id, out var guid ) )\r\n            throw new Exception( $\u0022\u0027{id}\u0027 isn\u0027t a guid - scene_tree and find_game_objects show object ids\u0022 );\r\n\r\n        foreach ( var session in SceneEditorSession.All.OrderBy( x =\u003E x != SceneEditorSession.Active ) )\r\n        {\r\n            var found = session.Scene?.Directory?.FindByGuid( guid );\r\n\r\n            // The scene registers itself in its own directory; a tool handed its id would act on the whole scene\r\n            if ( found is Scene )\r\n                throw new Exception( $\u0022{guid} is the scene itself, not a game object in it - scene_tree shows object ids\u0022 );\r\n\r\n            if ( found is not null ) return found;\r\n        }\r\n\r\n        throw new Exception( $\u0022No game object {guid} in any open scene\u0022 );\r\n    }\r\n\r\n    // Engine JSON accepts NaN and infinity, and every comparison with NaN is false, so no range check stops them\r\n    internal static void RequireFinite( string name, params float[] values )\r\n    {\r\n        if ( !values.All( float.IsFinite ) )\r\n            throw new Exception( $\u0022{name} must be finite - NaN and infinity aren\u0027t allowed\u0022 );\r\n    }\r\n\r\n    internal static void RequirePositive( string name, Vector3 v )\r\n    {\r\n        RequireFinite( name, v.x, v.y, v.z );\r\n\r\n        if ( v.x \u003C= 0 || v.y \u003C= 0 || v.z \u003C= 0 )\r\n            throw new Exception( $\u0022{name} {v} needs every component above zero\u0022 );\r\n    }\r\n\r\n    // Tool-supplied paths may only reach files inside the open project\r\n    internal static string ProjectPath( string path )\r\n    {\r\n        var root = Project.Current?.RootDirectory?.FullName ?? throw new Exception( \u0022No project is currently open\u0022 );\r\n        return ResolveInside( root, path, \u0022the project folder\u0022, \u0022heightmaps/island.png\u0022 );\r\n    }\r\n\r\n    // Prefab paths are relative to Assets, where the asset system registers them\r\n    internal static string AssetsPath( string path )\r\n    {\r\n        var root = Project.Current?.GetAssetsPath() ?? throw new Exception( \u0022No project is currently open\u0022 );\r\n        var full = ResolveInside( root, path, \u0022the Assets folder\u0022, \u0022prefabs/crate.prefab\u0022 );\r\n\r\n        if ( !full.EndsWith( \u0022.prefab\u0022, StringComparison.OrdinalIgnoreCase ) )\r\n            throw new Exception( $\u0022\u0027{path}\u0027 isn\u0027t a .prefab file - give a path like \u0027prefabs/crate.prefab\u0027\u0022 );\r\n\r\n        return full;\r\n    }\r\n\r\n    internal static string ResolveInside( string root, string path, string rootName, string example )\r\n    {\r\n        if ( string.IsNullOrWhiteSpace( path ) )\r\n            throw new Exception( $\u0022Give a path relative to {rootName}, e.g. \u0027{example}\u0027\u0022 );\r\n\r\n        root = Path.TrimEndingDirectorySeparator( Path.GetFullPath( root ) ) \u002B Path.DirectorySeparatorChar;\r\n\r\n        var full = Path.GetFullPath( Path.Combine( root, path.Replace( \u0027\\\\\u0027, \u0027/\u0027 ).TrimStart( \u0027/\u0027 ) ) );\r\n\r\n        if ( !full.StartsWith( root, StringComparison.OrdinalIgnoreCase ) )\r\n            throw new Exception( $\u0022\u0027{path}\u0027 resolves outside {rootName} - give a path relative to it, e.g. \u0027{example}\u0027\u0022 );\r\n\r\n        return full;\r\n    }\r\n}\r\n"},{"Ident":"arenula.leveltools","Path":"Editor/MeshEdgeTools.cs","FileName":"MeshEdgeTools.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":449884,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing Editor.Mcp;\r\nusing HalfEdgeMesh;\r\nusing Sandbox;\r\nusing static LevelTools.MeshEdit;\r\n\r\nnamespace LevelTools;\r\n\r\n[McpToolset( \u0022mesh\u0022 )]\r\npublic static class MeshEdgeTools\r\n{\r\n    /// \u003Csummary\u003E\r\n    /// Round off edges: replace each with a band of faces cut distance back into its neighbours. More\r\n    /// segments make a smoother curve; shape bends the band in or out. The user can undo this. Returns\r\n    /// the new faces\u0027 indices.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022edges\u0022\u003EEdge indices from mesh_get_info.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022distance\u0022\u003EHow far back from each edge to cut, in units. The engine shortens a cut wider than the neighbouring faces.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022segments\u0022\u003EFaces across the bevel, 1 to 32.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022shape\u0022\u003E-1 to 1. 0 is a straight chamfer or round curve, positive bulges out, negative in.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_bevel_edges\u0022 )]\r\n    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 )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handles = Edges( component.Mesh, edges );\r\n\r\n        RequireFinite( \u0022distance and shape\u0022, distance, shape );\r\n        if ( distance \u003C= 0 )\r\n            throw new Exception( \u0022Distance must be above 0\u0022 );\r\n\r\n        var added = new List\u003CFaceHandle\u003E();\r\n        var ok = Edit( session, component, \u0022Bevel Edges\u0022, mesh =\u003E\r\n        {\r\n            // The same mode and UV follow-up as the editor\u0027s bevel: faces the bevel can\u0027t texture are aligned to the grid\r\n            var needingUVs = new List\u003CFaceHandle\u003E();\r\n            if ( !mesh.BevelEdges( handles, PolygonMesh.BevelEdgesMode.RemoveClosedEdges, segments, distance, shape, outNewFaces: added, outFacesNeedingUVs: needingUVs ) )\r\n                return false;\r\n\r\n            foreach ( var face in needingUVs )\r\n                mesh.TextureAlignToGrid( mesh.Transform, face );\r\n\r\n            mesh.ComputeFaceTextureParametersFromCoordinates( added );\r\n            return true;\r\n        }, ok =\u003E ok );\r\n\r\n        if ( !ok )\r\n            throw Refused( \u0022bevel those edges\u0022 );\r\n\r\n        return new { Id = component.GameObject.Id, Faces = Indices( added ), Mesh = Counts( component.Mesh ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Cut corners off: replace each vertex with a small face whose corners sit distance along each edge\r\n    /// that met there. The user can undo this. Returns the new vertices\u0027 indices.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022vertices\u0022\u003EVertex indices from mesh_get_info.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022distance\u0022\u003EHow 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.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_bevel_vertices\u0022 )]\r\n    public static object BevelVertices( string id, int[] vertices, float distance = 5f )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handles = Vertices( component.Mesh, vertices );\r\n\r\n        RequireFinite( \u0022distance\u0022, distance );\r\n        if ( distance \u003C= 0 )\r\n            throw new Exception( \u0022Distance must be above 0\u0022 );\r\n\r\n        // The engine never refuses a cut that reaches the next vertex, or the other end\u0027s cut when both ends\r\n        // of an edge are bevelled; it collapses the corner into a degenerate mesh\r\n        var mesh = component.Mesh;\r\n        var limit = handles.Min( v =\u003E\r\n        {\r\n            mesh.GetEdgesConnectedToVertex( v, out var connected );\r\n            return connected.Min( e =\u003E\r\n            {\r\n                mesh.GetEdgeVertices( e, out var a, out var b );\r\n                var length = mesh.GetVertexPosition( a ).Distance( mesh.GetVertexPosition( b ) );\r\n                return handles.Contains( a == v ? b : a ) ? length / 2 : length;\r\n            } );\r\n        } );\r\n\r\n        if ( distance \u003E= limit )\r\n            throw new Exception( $\u0022Distance {distance} reaches the next vertex, or the cut from the other end where both ends of an edge are bevelled - stay under {limit:0.##}\u0022 );\r\n\r\n        var (ok, added) = Edit( session, component, \u0022Bevel Vertices\u0022, mesh =\u003E (mesh.BevelVertices( handles, distance, out var outVertices ), outVertices), r =\u003E r.Item1 );\r\n        if ( !ok )\r\n            throw Refused( \u0022bevel those vertices\u0022 );\r\n\r\n        return new { Id = component.GameObject.Id, Vertices = added?.Select( v =\u003E v.Index ).ToArray() ?? [], Mesh = Counts( component.Mesh ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Cut the mesh open along edges: each edge becomes two open edges with vertices of their own, so the\r\n    /// faces either side are no longer joined there. Nothing moves. The user can undo this. Returns the\r\n    /// two new open edges of each one.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022edges\u0022\u003EEdge indices from mesh_get_info.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_split_edges\u0022 )]\r\n    public static object SplitEdges( string id, int[] edges )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handles = Edges( component.Mesh, edges );\r\n\r\n        var (ok, a, b) = Edit( session, component, \u0022Split Edges\u0022, mesh =\u003E (mesh.SplitEdges( handles, out var halvesA, out var halvesB ), halvesA, halvesB), r =\u003E r.Item1 );\r\n        if ( !ok )\r\n            throw Refused( \u0022split those edges\u0022 );\r\n\r\n        return new { Id = component.GameObject.Id, EdgesA = EdgeIndices( a ), EdgesB = EdgeIndices( b ), Mesh = Counts( component.Mesh ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Remove edges and merge the faces either side of each into one; vertices left in a straight line are\r\n    /// removed too. mustBePlanar skips edges between faces that aren\u0027t flat with each other. The user can\r\n    /// undo this. Face indices change - call mesh_get_info again before the next edit.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022edges\u0022\u003EEdge indices from mesh_get_info.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022mustBePlanar\u0022\u003EOnly dissolve edges whose two faces lie in one plane.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_dissolve_edges\u0022 )]\r\n    public static object DissolveEdges( string id, int[] edges, bool mustBePlanar = false )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handles = Edges( component.Mesh, edges );\r\n        var before = Counts( component.Mesh ).Edges;\r\n\r\n        var removed = Edit( session, component, \u0022Dissolve Edges\u0022, mesh =\u003E\r\n        {\r\n            mesh.DissolveEdges( handles, mustBePlanar, PolygonMesh.DissolveRemoveVertexCondition.Colinear );\r\n            mesh.ComputeFaceTextureCoordinatesFromParameters();\r\n            return before - Counts( mesh ).Edges;\r\n        }, removed =\u003E removed \u003E 0 );\r\n\r\n        if ( removed == 0 )\r\n            throw new Exception( mustBePlanar ? \u0022None of those edges lie between coplanar faces, so nothing was dissolved\u0022 : Refused( \u0022dissolve those edges\u0022 ).Message );\r\n\r\n        return new { Id = component.GameObject.Id, EdgesRemoved = removed, Mesh = Counts( component.Mesh ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Join two open edges (Open in mesh_get_info, e.g. the rims of holes) with a new face between them.\r\n    /// The user can undo this. Returns the new face\u0027s index.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022edgeA\u0022\u003EThe first open edge\u0027s index.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022edgeB\u0022\u003EThe second open edge\u0027s index.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_bridge_edges\u0022 )]\r\n    public static object BridgeEdges( string id, int edgeA, int edgeB )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handles = Edges( component.Mesh, [edgeA, edgeB] );\r\n        if ( handles.Length \u003C 2 )\r\n            throw new Exception( $\u0022Edges {edgeA} and {edgeB} are the same edge - give two different open edges\u0022 );\r\n\r\n        foreach ( var edge in handles )\r\n        {\r\n            if ( !component.Mesh.IsEdgeOpen( edge ) )\r\n                throw new Exception( $\u0022Edge {edge.Index} has faces on both sides - bridging needs two open edges, the ones mesh_get_info marks Open\u0022 );\r\n        }\r\n\r\n        var (ok, face) = Edit( session, component, \u0022Bridge Edges\u0022, mesh =\u003E (mesh.BridgeEdges( handles[0], handles[1], out var newFace ), newFace), r =\u003E r.Item1 );\r\n        if ( !ok )\r\n            throw Refused( \u0022bridge those edges - they must border different faces\u0022 );\r\n\r\n        return new { Id = component.GameObject.Id, Face = face.Index, Mesh = Counts( component.Mesh ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Split a face by adding an edge between two of its vertices. Both vertices must be on the same face\r\n    /// and the new edge must stay inside it. The user can undo this. Returns the new edge\u0027s index.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022vertexA\u0022\u003EThe first vertex\u0027s index.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022vertexB\u0022\u003EThe second vertex\u0027s index.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_connect_vertices\u0022 )]\r\n    public static object ConnectVertices( string id, int vertexA, int vertexB )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handles = Vertices( component.Mesh, [vertexA, vertexB] );\r\n        if ( handles.Length \u003C 2 )\r\n            throw new Exception( \u0022Give two different vertices\u0022 );\r\n\r\n        var check = component.Mesh.CanConnectVertices( handles[0], handles[1] );\r\n        if ( check != PolygonMesh.ConnectVerticesResult.Success )\r\n        {\r\n            throw new Exception( check switch\r\n            {\r\n                PolygonMesh.ConnectVerticesResult.AlreadyConnected =\u003E $\u0022Vertices {vertexA} and {vertexB} already share an edge\u0022,\r\n                PolygonMesh.ConnectVerticesResult.NoSharedFace =\u003E $\u0022Vertices {vertexA} and {vertexB} aren\u0027t on the same face - mesh_get_info lists each face\u0027s vertices\u0022,\r\n                PolygonMesh.ConnectVerticesResult.OutsideFace =\u003E \u0022The edge would leave the face they share, which happens on concave faces - connect via another vertex\u0022,\r\n                PolygonMesh.ConnectVerticesResult.BothVerticesInternal =\u003E \u0022Both vertices are inside a face, not on its outline - at least one must be on the outline\u0022,\r\n                _ =\u003E \u0022Give two different vertices\u0022\r\n            } );\r\n        }\r\n\r\n        var (ok, edge) = Edit( session, component, \u0022Connect Vertices\u0022, mesh =\u003E (mesh.ConnectVertices( handles[0], handles[1], out var newEdge ), newEdge), r =\u003E r.Item1 );\r\n        if ( !ok )\r\n            throw Refused( \u0022connect those vertices\u0022 );\r\n\r\n        return new { Id = component.GameObject.Id, Edge = edge.Index, Mesh = Counts( component.Mesh ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Grow new faces out of open edges, each extended amount units outward in the plane of its face - to\r\n    /// widen a floor or continue a wall. The user can undo this. Returns the new faces and outer edges.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022edges\u0022\u003EOpen edge indices from mesh_get_info.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022amount\u0022\u003EHow far to extend, in units.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_extend_edges\u0022 )]\r\n    public static object ExtendEdges( string id, int[] edges, float amount )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handles = Edges( component.Mesh, edges );\r\n\r\n        RequireFinite( \u0022amount\u0022, amount );\r\n        if ( amount == 0 )\r\n            throw new Exception( \u0022Give a non-zero amount\u0022 );\r\n\r\n        if ( handles.FirstOrDefault( e =\u003E !component.Mesh.IsEdgeOpen( e ) ) is { IsValid: true } closed )\r\n            throw new Exception( $\u0022Edge {closed.Index} has faces on both sides - only open edges (Open in mesh_get_info) can be extended\u0022 );\r\n\r\n        var (ok, newEdges, newFaces) = Edit( session, component, \u0022Extend Edges\u0022, mesh =\u003E (mesh.ExtendEdges( handles, amount, out var outEdges, out var outFaces ), outEdges, outFaces), r =\u003E r.Item1 );\r\n        if ( !ok )\r\n            throw Refused( \u0022extend those edges\u0022 );\r\n\r\n        return new { Id = component.GameObject.Id, Edges = EdgeIndices( newEdges ), Faces = Indices( newFaces ), Mesh = Counts( component.Mesh ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Move one vertex to a new position in the object\u0027s local space; the faces using it follow. The user\r\n    /// can undo this.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022vertex\u0022\u003EThe vertex\u0027s index from mesh_get_info.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003ENew local position as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_set_vertex_position\u0022 )]\r\n    public static object SetVertexPosition( string id, int vertex, Vector3 position )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handle = Vertices( component.Mesh, [vertex] )[0];\r\n        RequireFinite( \u0022position\u0022, position.x, position.y, position.z );\r\n        var previous = component.Mesh.GetVertexPosition( handle );\r\n\r\n        Edit( session, component, \u0022Move Vertex\u0022, mesh =\u003E\r\n        {\r\n            mesh.SetVertexPosition( handle, position );\r\n\r\n            // The texture stays put while the faces move, as with the editor\u0027s texture lock off (its default)\r\n            mesh.ComputeFaceTextureCoordinatesFromParameters();\r\n            return 0;\r\n        } );\r\n\r\n        return new { Id = component.GameObject.Id, Vertex = vertex, Previous = previous, Position = position };\r\n    }\r\n\r\n    static int[] EdgeIndices( IEnumerable\u003CHalfEdgeHandle\u003E edges ) =\u003E edges?.Where( e =\u003E e.IsValid ).Select( e =\u003E e.Index ).ToArray() ?? [];\r\n}\r\n"},{"Ident":"arenula.leveltools","Path":"Editor/TerrainEdit.cs","FileName":"TerrainEdit.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":449884,"IsPrivate":false,"Code":"using System;\r\nusing System.Linq;\r\nusing Editor;\r\nusing Sandbox;\r\nusing static LevelTools.McpHelpers;\r\n\r\nnamespace LevelTools;\r\n\r\n/// \u003Csummary\u003E\r\n/// The texels a circular brush covers. Region is the clamped bounding rectangle, the unit of undo.\r\n/// \u003C/summary\u003E\r\ninternal readonly record struct TerrainBrush( Vector2Int Centre, int Radius, RectInt Region, int Resolution )\r\n{\r\n    /// \u003Csummary\u003EVisit each texel inside the circle with its index, offset from the centre and distance (0 centre, 1 rim).\u003C/summary\u003E\r\n    public int ForEach( Action\u003Cint, int, int, float\u003E visit )\r\n    {\r\n        var count = 0;\r\n        for ( var y = Region.Top; y \u003C Region.Top \u002B Region.Height; y\u002B\u002B )\r\n        {\r\n            for ( var x = Region.Left; x \u003C Region.Left \u002B Region.Width; x\u002B\u002B )\r\n            {\r\n                int dx = x - Centre.x, dy = y - Centre.y;\r\n                var distance = MathF.Sqrt( dx * dx \u002B dy * dy );\r\n                if ( distance \u003E Radius ) continue;\r\n\r\n                visit( y * Resolution \u002B x, dx, dy, distance / Radius );\r\n                count\u002B\u002B;\r\n            }\r\n        }\r\n\r\n        return count;\r\n    }\r\n}\r\n\r\ninternal static class TerrainEdit\r\n{\r\n    internal static RectInt Whole( Terrain terrain ) =\u003E new( 0, 0, terrain.Storage.Resolution, terrain.Storage.Resolution );\r\n\r\n    internal static Terrain ForRead( string id ) =\u003E Find( id, ReadScene() );\r\n\r\n    internal static (Terrain Terrain, SceneEditorSession Session) ForEdit( string id )\r\n    {\r\n        var terrain = Find( id, ActiveSession().Scene );\r\n\r\n        // A disabled terrain has no GPU textures, so its edits could not be shown or collided with\r\n        if ( !terrain.Active )\r\n            throw new Exception( $\u0022\u0027{terrain.GameObject.Name}\u0027 is disabled - enable it with set_game_object before editing it\u0022 );\r\n\r\n        return (terrain, SessionOf( terrain.GameObject ));\r\n    }\r\n\r\n    // An empty id means the scene\u0027s only terrain, the usual case\r\n    static Terrain Find( string id, Scene scene )\r\n    {\r\n        Terrain terrain;\r\n\r\n        if ( !string.IsNullOrWhiteSpace( id ) )\r\n        {\r\n            var go = FindByGuid( id );\r\n            terrain = go.Components.Get\u003CTerrain\u003E( FindMode.EverythingInSelf )\r\n                ?? throw new Exception( $\u0022\u0027{go.Name}\u0027 has no Terrain component - call terrain_get_info without an id to find the scene\u0027s terrain\u0022 );\r\n        }\r\n        else\r\n        {\r\n            // GetAllComponents skips disabled terrains, which would send the caller off to create a duplicate\r\n            var all = scene.Components.GetAll\u003CTerrain\u003E( FindMode.EverythingInDescendants ).ToArray();\r\n            terrain = all.Length switch\r\n            {\r\n                0 =\u003E throw new Exception( \u0022The scene has no terrain - make one with terrain_create\u0022 ),\r\n                1 =\u003E all[0],\r\n                _ =\u003E throw new Exception( $\u0022The scene has {all.Length} terrains - pass the id of one: {string.Join( \u0022, \u0022, all.Select( x =\u003E $\u0022\u0027{x.GameObject.Name}\u0027 {x.GameObject.Id}{(x.Active ? \u0022\u0022 : \u0022 (disabled)\u0022)}\u0022 ) )}\u0022 )\r\n            };\r\n        }\r\n\r\n        if ( terrain.Storage is null )\r\n            throw new Exception( $\u0022\u0027{terrain.GameObject.Name}\u0027 has no terrain data - select it in the editor to give it some, or use terrain_create\u0022 );\r\n\r\n        return terrain;\r\n    }\r\n\r\n    internal static float HeightOf( Terrain terrain, ushort raw ) =\u003E raw / (float)ushort.MaxValue * terrain.Storage.TerrainHeight;\r\n\r\n    // Rounded, not truncated: float error puts some HeightOf round trips just under the raw value, and truncation would lower them a step\r\n    internal static ushort RawOf( Terrain terrain, float height ) =\u003E (ushort)MathF.Round( Math.Clamp( height / terrain.Storage.TerrainHeight, 0f, 1f ) * ushort.MaxValue );\r\n\r\n    /// \u003Csummary\u003EThe texel under a world position, through the terrain\u0027s transform. Null when it is off the terrain.\u003C/summary\u003E\r\n    internal static Vector2Int? TexelAt( Terrain terrain, Vector3 world )\r\n    {\r\n        var texel = UnclampedTexel( terrain, world );\r\n        var res = terrain.Storage.Resolution;\r\n        return texel.x \u003C 0 || texel.y \u003C 0 || texel.x \u003E= res || texel.y \u003E= res ? null : texel;\r\n    }\r\n\r\n    internal static Vector2Int RequireTexel( Terrain terrain, Vector3 world )\r\n    {\r\n        return TexelAt( terrain, world )\r\n            ?? throw new Exception( $\u0022{world} is off the terrain \u0027{terrain.GameObject.Name}\u0027 - terrain_get_info shows its position and size\u0022 );\r\n    }\r\n\r\n    internal static TerrainBrush BrushAt( Terrain terrain, Vector3 world, float radius )\r\n    {\r\n        RequireFinite( \u0022position and radius\u0022, world.x, world.y, world.z, radius );\r\n        if ( radius \u003C= 0 )\r\n            throw new Exception( $\u0022Radius must be above zero, got {radius}\u0022 );\r\n\r\n        var storage = terrain.Storage;\r\n        var res = storage.Resolution;\r\n        var centre = UnclampedTexel( terrain, world );\r\n        var texels = Math.Max( 1, (int)(radius / terrain.WorldScale.x / storage.TerrainSize * res) );\r\n\r\n        int left = Math.Max( 0, centre.x - texels ), top = Math.Max( 0, centre.y - texels );\r\n        int right = Math.Min( res, centre.x \u002B texels \u002B 1 ), bottom = Math.Min( res, centre.y \u002B texels \u002B 1 );\r\n\r\n        if ( right \u003C= left || bottom \u003C= top )\r\n            throw new Exception( $\u0022A radius {radius} brush at {world} doesn\u0027t reach the terrain \u0027{terrain.GameObject.Name}\u0027 - terrain_get_info shows its position and size\u0022 );\r\n\r\n        return new TerrainBrush( centre, texels, new RectInt( left, top, right - left, bottom - top ), res );\r\n    }\r\n\r\n    static Vector2Int UnclampedTexel( Terrain terrain, Vector3 world )\r\n    {\r\n        var local = terrain.WorldTransform.PointToLocal( world );\r\n        var scale = terrain.Storage.Resolution / terrain.Storage.TerrainSize;\r\n        return new Vector2Int( (int)MathF.Floor( local.x * scale ), (int)MathF.Floor( local.y * scale ) );\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Run an edit of one map and push it to rendering and collision, with undo. Mirrors the engine\u0027s\r\n    /// own brush tools: the region is copied before and after, and undo or redo copies it back.\r\n    /// \u003C/summary\u003E\r\n    internal static void Commit\u003CT\u003E( SceneEditorSession session, Terrain terrain, string undoName, Func\u003CTerrainStorage, T[]\u003E mapOf,\r\n        Terrain.SyncFlags flags, RectInt region, Action edit ) where T : unmanaged\r\n    {\r\n        var before = Copy( mapOf( terrain.Storage ), terrain.Storage.Resolution, region );\r\n        edit();\r\n        var after = Copy( mapOf( terrain.Storage ), terrain.Storage.Resolution, region );\r\n\r\n        terrain.ApplyStorageChanges( flags, region );\r\n\r\n        // Resolved by id at undo time: undoing and redoing the terrain\u0027s creation replaces the component instance\r\n        var scene = session.Scene;\r\n        var componentId = terrain.Id;\r\n\r\n        Action Restore( T[] data ) =\u003E () =\u003E\r\n        {\r\n            if ( scene.Directory.FindComponentByGuid( componentId ) is not Terrain target || target.Storage is null )\r\n                return;\r\n\r\n            var map = mapOf( target.Storage );\r\n            for ( var y = 0; y \u003C region.Height; y\u002B\u002B )\r\n                Array.Copy( data, y * region.Width, map, (region.Top \u002B y) * target.Storage.Resolution \u002B region.Left, region.Width );\r\n\r\n            target.ApplyStorageChanges( flags, region );\r\n        };\r\n\r\n        session.AddUndo( undoName, Restore( before ), Restore( after ) );\r\n        session.HasUnsavedChanges = true;\r\n    }\r\n\r\n    internal static void CommitHeights( SceneEditorSession session, Terrain terrain, string undoName, RectInt region, Action edit )\r\n        =\u003E Commit( session, terrain, undoName, s =\u003E s.HeightMap, Terrain.SyncFlags.Height, region, edit );\r\n\r\n    internal static void CommitControl( SceneEditorSession session, Terrain terrain, string undoName, RectInt region, Action edit )\r\n        =\u003E Commit( session, terrain, undoName, s =\u003E s.ControlMap, Terrain.SyncFlags.Control, region, edit );\r\n\r\n    static T[] Copy\u003CT\u003E( T[] map, int resolution, RectInt region ) where T : unmanaged\r\n    {\r\n        var copy = new T[region.Width * region.Height];\r\n        for ( var y = 0; y \u003C region.Height; y\u002B\u002B )\r\n            Array.Copy( map, (region.Top \u002B y) * resolution \u002B region.Left, copy, y * region.Width, region.Width );\r\n        return copy;\r\n    }\r\n}\r\n"},{"Ident":"arenula.leveltools","Path":"Editor/MeshEdit.cs","FileName":"MeshEdit.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":449884,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing Editor;\r\nusing HalfEdgeMesh;\r\nusing Sandbox;\r\nusing Sandbox.Helpers;\r\nusing static LevelTools.McpHelpers;\r\n\r\nnamespace LevelTools;\r\n\r\ninternal readonly record struct MeshCounts( int Faces, int Vertices, int Edges );\r\n\r\ninternal static class MeshEdit\r\n{\r\n    internal const string DefaultMaterial = \u0022materials/dev/reflectivity_30.vmat\u0022;\r\n\r\n    internal static MeshComponent ForRead( string id )\r\n    {\r\n        var go = FindByGuid( id );\r\n        var mesh = go.Components.Get\u003CMeshComponent\u003E( FindMode.EverythingInSelf )\r\n            ?? throw new Exception( $\u0022\u0027{go.Name}\u0027 has no MeshComponent - the mesh_create tools make one\u0022 );\r\n\r\n        if ( mesh.Mesh is null )\r\n            throw new Exception( $\u0022\u0027{go.Name}\u0027 has a MeshComponent with no mesh in it - make one with the mesh_create tools\u0022 );\r\n\r\n        return mesh;\r\n    }\r\n\r\n    internal static (MeshComponent Mesh, SceneEditorSession Session) ForEdit( string id )\r\n    {\r\n        var mesh = ForRead( id );\r\n\r\n        // A disabled MeshComponent builds no model, so an edit could be neither seen nor collided with\r\n        if ( !mesh.Active )\r\n            throw new Exception( $\u0022\u0027{mesh.GameObject.Name}\u0027 is disabled - enable it with set_game_object before editing it\u0022 );\r\n\r\n        return (mesh, SessionOf( mesh.GameObject ));\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Run an edit with the component snapshot the engine\u0027s own mesh tools take, so undo and redo\r\n    /// restore the whole mesh and find the component by id themselves. When the edit throws or\r\n    /// succeeded says it failed, the entry this call recorded is restored and removed and the redo\r\n    /// history it cleared is put back, so the mesh and both undo stacks are as they were - only then\r\n    /// does this return or rethrow. If that can\u0027t be done (no entry was recorded, or restoring it\r\n    /// threw) it throws instead, saying the mesh may be partly changed. Refuse predictable failures\r\n    /// before calling this, so they never touch the undo history.\r\n    /// \u003C/summary\u003E\r\n    internal static T Edit\u003CT\u003E( SceneEditorSession session, MeshComponent component, string undoName, Func\u003CPolygonMesh, T\u003E edit, Func\u003CT, bool\u003E succeeded = null )\r\n    {\r\n        var history = session.UndoSystem;\r\n        history.Back.TryPeek( out var before );\r\n        var redo = history.Forward.ToArray();\r\n        T result;\r\n\r\n        try\r\n        {\r\n            using var sceneScope = session.Scene.Push();\r\n            using var undoScope = session.UndoScope( undoName ).WithComponentChanges( component ).Push();\r\n\r\n            result = edit( component.Mesh );\r\n            component.RebuildMesh();\r\n        }\r\n        catch ( Exception e )\r\n        {\r\n            RollBack( history, before, redo, $\u0022{undoName} failed ({e.Message})\u0022, e );\r\n            throw;\r\n        }\r\n\r\n        if ( succeeded?.Invoke( result ) == false )\r\n            RollBack( history, before, redo, $\u0022{undoName} was refused\u0022, null );\r\n\r\n        return result;\r\n    }\r\n\r\n    static void RollBack( UndoSystem history, UndoSystem.Entry before, UndoSystem.Entry[] redo, string failure, Exception cause )\r\n    {\r\n        // When the scope\u0027s snapshot throws it records nothing, and the top entry is then the user\u0027s own\r\n        if ( !history.Back.TryPeek( out var failed ) || ReferenceEquals( failed, before ) )\r\n            throw new Exception( $\u0022{failure} and recorded no undo entry to roll back with, so the mesh may be partly changed - check it with mesh_get_info\u0022, cause );\r\n\r\n        // Not UndoSystem.Undo(): it logs and swallows a failed restore, and would leave the failed edit on the redo stack\r\n        try\r\n        {\r\n            failed.Undo();\r\n        }\r\n        catch ( Exception e )\r\n        {\r\n            throw new Exception( $\u0022{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\u0022, cause ?? e );\r\n        }\r\n\r\n        history.Back.Pop();\r\n\r\n        // Recording the failed edit cleared the redo history; with the mesh restored those entries apply again\r\n        history.Forward.Clear();\r\n        foreach ( var entry in redo.Reverse() )\r\n            history.Forward.Push( entry );\r\n    }\r\n\r\n    internal static MeshComponent Create( string name, Vector3? position, string material, Vector3[] vertices, int[][] faces )\r\n    {\r\n        if ( position is { } p )\r\n            RequireFinite( \u0022position\u0022, p.x, p.y, p.z );\r\n\r\n        var session = ActiveSession();\r\n        var mat = LoadMaterial( material );\r\n\r\n        var mesh = new PolygonMesh();\r\n        var handles = mesh.AddVertices( vertices );\r\n        foreach ( var face in faces )\r\n            mesh.SetFaceMaterial( mesh.AddFace( face.Select( i =\u003E handles[i] ).ToArray() ), mat );\r\n\r\n        mesh.TextureAlignToGrid( Transform.Zero );\r\n\r\n        using var sceneScope = session.Scene.Push();\r\n        using var undoScope = session.UndoScope( $\u0022Create {name}\u0022 ).WithGameObjectCreations().Push();\r\n\r\n        // The same setup as the editor\u0027s block tool (PrimitiveTool.Create)\r\n        var go = new GameObject( true, name );\r\n        go.WorldPosition = position ?? Vector3.Zero;\r\n        go.IsStatic = true;\r\n\r\n        var component = go.Components.Create\u003CMeshComponent\u003E( false );\r\n        component.Mesh = mesh;\r\n        component.SmoothingAngle = 40f;\r\n        component.Enabled = true;\r\n\r\n        return component;\r\n    }\r\n\r\n    internal static object Created( MeshComponent component )\r\n    {\r\n        return new { Id = component.GameObject.Id, Name = component.GameObject.Name, Position = component.WorldPosition, Mesh = Counts( component.Mesh ) };\r\n    }\r\n\r\n    // A missing path loads as the error material instead of failing, so check the file first\r\n    internal static Material LoadMaterial( string path )\r\n    {\r\n        if ( string.IsNullOrWhiteSpace( path ) || !Sandbox.FileSystem.Mounted.FileExists( path ) \u0026\u0026 !Sandbox.FileSystem.Mounted.FileExists( path \u002B \u0022_c\u0022 ) )\r\n            throw new Exception( $\u0022No material \u0027{path}\u0027 - find materials with asset_search type:vmat\u0022 );\r\n\r\n        return Material.Load( path );\r\n    }\r\n\r\n    /// \u003Csummary\u003EOne half-edge per edge, the lower index of the pair - the index get_info shows.\u003C/summary\u003E\r\n    internal static IEnumerable\u003CHalfEdgeHandle\u003E Edges( PolygonMesh mesh ) =\u003E mesh.HalfEdgeHandles.Where( h =\u003E FullEdge( mesh, h ) == h );\r\n\r\n    /// \u003Csummary\u003EThe half-edge an edge is known by: the lower index of the pair, as the engine\u0027s own full-edge lookup picks.\u003C/summary\u003E\r\n    internal static HalfEdgeHandle FullEdge( PolygonMesh mesh, HalfEdgeHandle h )\r\n    {\r\n        var opposite = mesh.GetOppositeHalfEdge( h );\r\n        return opposite.IsValid \u0026\u0026 opposite.Index \u003C h.Index ? opposite : h;\r\n    }\r\n\r\n    internal static int[] Indices( IEnumerable\u003CFaceHandle\u003E faces ) =\u003E faces?.Where( f =\u003E f.IsValid ).Select( f =\u003E f.Index ).ToArray() ?? [];\r\n\r\n    internal static Exception Refused( string what ) =\u003E\r\n        new( $\u0022The engine couldn\u0027t {what}. The mesh is unchanged - check the indices with mesh_get_info\u0022 );\r\n\r\n    internal static MeshCounts Counts( PolygonMesh mesh ) =\u003E new( mesh.FaceHandles.Count(), mesh.VertexHandles.Count(), Edges( mesh ).Count() );\r\n\r\n    internal static FaceHandle[] Faces( PolygonMesh mesh, int[] indices ) =\u003E Handles( indices, \u0022face\u0022, mesh.FaceHandleFromIndex, h =\u003E h.IsValid );\r\n\r\n    internal static FaceHandle[] FacesOrAll( PolygonMesh mesh, int[] indices ) =\u003E indices is { Length: \u003E 0 } ? Faces( mesh, indices ) : mesh.FaceHandles.ToArray();\r\n\r\n    internal static VertexHandle[] Vertices( PolygonMesh mesh, int[] indices ) =\u003E Handles( indices, \u0022vertex\u0022, mesh.VertexHandleFromIndex, h =\u003E h.IsValid );\r\n\r\n    // The engine matches its results against full edges, and would act twice on an edge given by both halves\r\n    internal static HalfEdgeHandle[] Edges( PolygonMesh mesh, int[] indices ) =\u003E\r\n        Handles( indices, \u0022edge\u0022, mesh.HalfEdgeHandleFromIndex, h =\u003E h.IsValid ).Select( h =\u003E FullEdge( mesh, h ) ).DistinctBy( h =\u003E h.Index ).ToArray();\r\n\r\n    // The mesh tool files import only MeshEdit statically, so they reach the shared check through here\r\n    internal static void RequireFinite( string name, params float[] values ) =\u003E McpHelpers.RequireFinite( name, values );\r\n\r\n    static T[] Handles\u003CT\u003E( int[] indices, string kind, Func\u003Cint, T\u003E fromIndex, Func\u003CT, bool\u003E isValid )\r\n    {\r\n        if ( indices is null || indices.Length == 0 )\r\n            throw new Exception( $\u0022Give at least one {kind} index - mesh_get_info lists them\u0022 );\r\n\r\n        return indices.Distinct().Select( i =\u003E\r\n        {\r\n            var handle = i \u003E= 0 ? fromIndex( i ) : default;\r\n            return i \u003E= 0 \u0026\u0026 isValid( handle ) ? handle : throw new Exception( $\u0022The mesh has no {kind} {i} - mesh_get_info lists its {kind} indices\u0022 );\r\n        } ).ToArray();\r\n    }\r\n}\r\n"},{"Ident":"arenula.leveltools","Path":"Editor/MeshFaceTools.cs","FileName":"MeshFaceTools.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":449884,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing Editor.Mcp;\r\nusing HalfEdgeMesh;\r\nusing Sandbox;\r\nusing static LevelTools.MeshEdit;\r\n\r\nnamespace LevelTools;\r\n\r\n[McpToolset( \u0022mesh\u0022 )]\r\npublic static class MeshFaceTools\r\n{\r\n    /// \u003Csummary\u003E\r\n    /// Extrude faces: move them out and join them to where they were with new side faces. By default\r\n    /// they move along their average normal by distance; offset moves them by an exact local vector\r\n    /// instead. The user can undo this. Returns the moved and the new side faces\u0027 indices.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022faces\u0022\u003EFace indices from mesh_get_info.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022distance\u0022\u003EHow far to move the faces along their average normal. Negative pushes them in.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022offset\u0022\u003EExact offset as \u0027x,y,z\u0027 in the object\u0027s local space. Overrides distance.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_extrude_faces\u0022 )]\r\n    public static object ExtrudeFaces( string id, int[] faces, float distance = 50f, Vector3? offset = null )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handles = Faces( component.Mesh, faces );\r\n\r\n        RequireFinite( \u0022distance\u0022, distance );\r\n        if ( offset is { } o )\r\n            RequireFinite( \u0022offset\u0022, o.x, o.y, o.z );\r\n\r\n        var move = offset ?? AverageNormal( component.Mesh, handles ) * distance;\r\n        if ( move.IsNearlyZero() )\r\n            throw new Exception( \u0022That extrusion moves the faces nowhere - give a non-zero distance, or an offset when the faces\u0027 normals cancel out\u0022 );\r\n\r\n        var (moved, sides) = Edit( session, component, \u0022Extrude Faces\u0022, mesh =\u003E\r\n        {\r\n            mesh.ExtrudeFaces( handles, out var newFaces, out var connecting, move );\r\n            return (newFaces, connecting);\r\n        } );\r\n\r\n        return new { Id = component.GameObject.Id, Offset = move, Faces = Indices( moved ), SideFaces = Indices( sides ), Mesh = Counts( component.Mesh ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Delete faces, leaving a hole with open edges. Vertices no face uses any more go too. The user can\r\n    /// undo this. Indices of other faces can change - call mesh_get_info again before the next edit.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022faces\u0022\u003EFace indices from mesh_get_info.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_remove_faces\u0022 )]\r\n    public static object RemoveFaces( string id, int[] faces )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handles = Faces( component.Mesh, faces );\r\n\r\n        Edit( session, component, \u0022Remove Faces\u0022, mesh =\u003E\r\n        {\r\n            mesh.RemoveFaces( handles );\r\n            return 0;\r\n        } );\r\n\r\n        return new { Id = component.GameObject.Id, Removed = handles.Length, Mesh = Counts( component.Mesh ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Add a face through existing vertices, e.g. to fill a hole left by mesh_remove_faces. List the\r\n    /// vertices counter-clockwise as seen from the side the face should face. The user can undo this.\r\n    /// Returns the new face\u0027s index.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022vertices\u0022\u003EThree or more vertex indices from mesh_get_info, in winding order.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022material\u0022\u003EMaterial asset path for the face. Empty uses the material of a face it borders, or leaves it with none if it borders no face.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_add_face\u0022 )]\r\n    public static object AddFace( string id, int[] vertices, string material = \u0022\u0022 )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handles = Vertices( component.Mesh, vertices );\r\n\r\n        if ( handles.Length \u003C vertices.Length )\r\n            throw new Exception( \u0022A vertex appears twice - list each corner of the face once\u0022 );\r\n\r\n        if ( handles.Length \u003C 3 )\r\n            throw new Exception( \u0022A face needs at least three vertices\u0022 );\r\n\r\n        var mat = string.IsNullOrWhiteSpace( material ) ? null : LoadMaterial( material );\r\n\r\n        var face = Edit( session, component, \u0022Add Face\u0022, mesh =\u003E\r\n        {\r\n            var added = mesh.AddFace( handles );\r\n            if ( !added.IsValid ) return added;\r\n\r\n            // The engine leaves a new face with no material; a filled hole should match the faces around it\r\n            var paint = mat ?? (mesh.GetFacesConnectedToFace( added, out var around ) ? around.Select( mesh.GetFaceMaterial ).FirstOrDefault( m =\u003E m is not null ) : null);\r\n            if ( paint is not null ) mesh.AssignMaterialToFaces( [added], paint );\r\n\r\n            // AddFace leaves the texture axes zero, so every corner would share one UV; the engine\u0027s hole fill aligns too\r\n            mesh.TextureAlignToGrid( mesh.Transform, added );\r\n            return added;\r\n        }, added =\u003E added.IsValid );\r\n\r\n        if ( !face.IsValid )\r\n            throw new Exception( \u0022Those vertices can\u0027t make a face - each edge can only border one face per side, so try the opposite winding or vertices around an open hole (Open edges in mesh_get_info)\u0022 );\r\n\r\n        return new { Id = component.GameObject.Id, Face = face.Index, Mesh = Counts( component.Mesh ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Cut faces along a plane in the object\u0027s local space, splitting every face it crosses. Faces on the\r\n    /// side the normal points away from are removed unless keepBoth is set, and the cut can be capped to\r\n    /// close the mesh. The user can undo this. Returns the cap faces\u0027 indices.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022point\u0022\u003EA point on the plane as \u0027x,y,z\u0027, local space.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022normal\u0022\u003EThe plane\u0027s normal as \u0027x,y,z\u0027. Faces in front of it are kept.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022faces\u0022\u003EFace indices to cut. Empty cuts the whole mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022keepBoth\u0022\u003ESplit faces along the plane but remove nothing.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022cap\u0022\u003EClose the cut with new faces where possible.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_clip_faces\u0022 )]\r\n    public static object ClipFaces( string id, Vector3 point, Vector3 normal, int[] faces = null, bool keepBoth = false, bool cap = true )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handles = FacesOrAll( component.Mesh, faces );\r\n\r\n        RequireFinite( \u0022point and normal\u0022, point.x, point.y, point.z, normal.x, normal.y, normal.z );\r\n        if ( normal.IsNearlyZero() )\r\n            throw new Exception( \u0022The plane normal can\u0027t be zero\u0022 );\r\n\r\n        var capFaces = new List\u003CFaceHandle\u003E();\r\n        var newEdges = new List\u003CHalfEdgeHandle\u003E();\r\n        Edit( session, component, \u0022Clip Faces\u0022, mesh =\u003E\r\n        {\r\n            mesh.ClipFacesByPlaneAndCap( handles, new Plane( point, normal.Normal ), !keepBoth, cap, newEdges, capFaces );\r\n            return 0;\r\n        } );\r\n\r\n        return new { Id = component.GameObject.Id, NewEdges = newEdges.Count, CapFaces = Indices( capFaces ), Mesh = Counts( component.Mesh ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Give faces thickness: copies them amount units back along their normals and joins the copy to the\r\n    /// original with side faces - a plane becomes a slab. Every edge on the outline of the faces must be\r\n    /// open, as on a plane or around a hole. The user can undo this. Returns the thickened faces\u0027 indices,\r\n    /// which are the ones given.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022faces\u0022\u003EFace indices from mesh_get_info.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022amount\u0022\u003EThickness in units. Negative thickens toward the front.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_thicken_faces\u0022 )]\r\n    public static object ThickenFaces( string id, int[] faces, float amount )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handles = Faces( component.Mesh, faces );\r\n\r\n        RequireFinite( \u0022amount\u0022, amount );\r\n        if ( amount == 0 )\r\n            throw new Exception( \u0022Give a non-zero amount\u0022 );\r\n\r\n        // The engine skips any face island with a closed edge on its outline, and refuses when that leaves none\r\n        component.Mesh.FindBoundaryEdgesConnectedToFaces( handles, out var boundary );\r\n        var closed = boundary.Where( e =\u003E !component.Mesh.IsEdgeOpen( e ) ).Select( e =\u003E FullEdge( component.Mesh, e ).Index ).FirstOrDefault( -1 );\r\n        if ( boundary.Count == 0 || closed \u003E= 0 )\r\n            throw new Exception( $\u0022Only faces whose outline is all open edges can be thickened, like a plane or a shell with a hole - {(closed \u003E= 0 ? $\u0022edge {closed} borders another face\u0022 : \u0022those faces have no outline\u0022)}; mesh_get_info marks open edges\u0022 );\r\n\r\n        var (ok, added) = Edit( session, component, \u0022Thicken Faces\u0022, mesh =\u003E\r\n        {\r\n            var thickened = mesh.ThickenFaces( handles, amount, out var outFaces );\r\n            mesh.ComputeFaceTextureCoordinatesFromParameters();\r\n            return (thickened, outFaces);\r\n        }, r =\u003E r.Item1 );\r\n        if ( !ok )\r\n            throw Refused( \u0022thicken those faces\u0022 );\r\n\r\n        return new { Id = component.GameObject.Id, Faces = Indices( added ), Mesh = Counts( component.Mesh ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Slice faces into a grid of cutsX by cutsY extra cuts, measured along each face\u0027s own corners. Works\r\n    /// best on four-cornered faces. The user can undo this. Returns the resulting faces\u0027 indices.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022faces\u0022\u003EFace indices from mesh_get_info.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022cutsX\u0022\u003ECuts across the first direction, 0 to 64.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022cutsY\u0022\u003ECuts across the second direction, 0 to 64.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_quad_slice_faces\u0022 )]\r\n    public static object QuadSliceFaces( string id, int[] faces, [Sandbox.Range( 0, 64 )] int cutsX = 1, [Sandbox.Range( 0, 64 )] int cutsY = 1 )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n        var handles = Faces( component.Mesh, faces );\r\n\r\n        if ( cutsX \u002B cutsY == 0 )\r\n            throw new Exception( \u0022Give at least one cut\u0022 );\r\n\r\n        var added = new List\u003CFaceHandle\u003E();\r\n        Edit( session, component, \u0022Quad Slice Faces\u0022, mesh =\u003E\r\n        {\r\n            // 60 degrees is the corner angle the editor\u0027s slice uses to find a face\u0027s four corners\r\n            mesh.QuadSliceFaces( handles, cutsX, cutsY, 60f, added );\r\n\r\n            // The slice leaves the new faces\u0027 UVs unset; the editor\u0027s slice recomputes them the same way\r\n            mesh.ComputeFaceTextureCoordinatesFromParameters();\r\n            return 0;\r\n        } );\r\n\r\n        return new { Id = component.GameObject.Id, Faces = Indices( added ), Mesh = Counts( component.Mesh ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Turn every face of the mesh inside out, reversing its normals - for a mesh that renders inside out\r\n    /// or that should be seen from inside, like a room. The user can undo this.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_flip_faces\u0022 )]\r\n    public static object FlipFaces( string id )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n\r\n        Edit( session, component, \u0022Flip Faces\u0022, mesh =\u003E\r\n        {\r\n            mesh.FlipAllFaces();\r\n            return 0;\r\n        } );\r\n\r\n        return new { Id = component.GameObject.Id, Mesh = Counts( component.Mesh ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Scale the mesh\u0027s vertices about the object\u0027s origin, changing its geometry rather than the\r\n    /// object\u0027s transform (set_game_object does that). The user can undo this. Returns the new local bounds.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id of the mesh.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022scale\u0022\u003EScale factor per axis as \u0027x,y,z\u0027, e.g. \u00272,2,1\u0027. A negative factor mirrors the mesh; its faces are flipped to keep facing outward.\u003C/param\u003E\r\n    [McpTool( \u0022mesh_scale_mesh\u0022 )]\r\n    public static object ScaleMesh( string id, Vector3 scale )\r\n    {\r\n        var (component, session) = ForEdit( id );\r\n\r\n        RequireFinite( \u0022scale\u0022, scale.x, scale.y, scale.z );\r\n        if ( scale.x == 0 || scale.y == 0 || scale.z == 0 )\r\n            throw new Exception( \u0022A zero scale would flatten the mesh - give every axis a non-zero factor\u0022 );\r\n\r\n        Edit( session, component, \u0022Scale Mesh\u0022, mesh =\u003E\r\n        {\r\n            mesh.Scale( scale );\r\n\r\n            // The texture stretches with the mesh, as the editor\u0027s scale bake does\r\n            mesh.ComputeFaceTextureParametersFromCoordinates();\r\n\r\n            // An odd number of negative axes mirrors the mesh and reverses its winding, as the editor\u0027s mirror tool corrects for\r\n            if ( (scale.x \u003C 0) ^ (scale.y \u003C 0) ^ (scale.z \u003C 0) )\r\n                mesh.FlipAllFaces();\r\n\r\n            return 0;\r\n        } );\r\n\r\n        var bounds = component.Mesh.CalculateBounds();\r\n        return new { Id = component.GameObject.Id, Bounds = new { bounds.Mins, bounds.Maxs } };\r\n    }\r\n\r\n    static Vector3 AverageNormal( PolygonMesh mesh, FaceHandle[] faces )\r\n    {\r\n        var sum = Vector3.Zero;\r\n        foreach ( var face in faces )\r\n        {\r\n            mesh.ComputeFaceNormal( face, out var normal );\r\n            sum \u002B= normal;\r\n        }\r\n\r\n        return sum.Normal;\r\n    }\r\n}\r\n"},{"Ident":"arenula.leveltools","Path":"Editor/TerrainMaterialTools.cs","FileName":"TerrainMaterialTools.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":449884,"IsPrivate":false,"Code":"using System;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing Editor;\r\nusing Editor.Mcp;\r\nusing Sandbox;\r\nusing static LevelTools.McpHelpers;\r\nusing static LevelTools.TerrainEdit;\r\n\r\nnamespace LevelTools;\r\n\r\n[McpToolset( \u0022terrain\u0022 )]\r\npublic static class TerrainMaterialTools\r\n{\r\n    // The control map packs material indices into 5 bits\r\n    const int MaxMaterials = 32;\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Add a terrain material (.tmat) to a terrain\u0027s material list. Its index is what terrain_paint_material\r\n    /// and terrain_blend_materials paint with; a material already in the list keeps its index. The user\r\n    /// can undo this. Find materials with asset_search type:tmat.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022materialPath\u0022\u003ETerrain material asset path, e.g. \u0027materials/terrain/snow_02.tmat\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003ETerrain game object id. Empty means the scene\u0027s only terrain.\u003C/param\u003E\r\n    [McpTool( \u0022terrain_add_material\u0022 )]\r\n    public static object AddMaterial( string materialPath, string id = \u0022\u0022 )\r\n    {\r\n        var (terrain, session) = ForEdit( id );\r\n        var materials = terrain.Storage.Materials;\r\n\r\n        var material = ResourceLibrary.Get\u003CTerrainMaterial\u003E( materialPath )\r\n            ?? throw new Exception( $\u0022No terrain material at \u0027{materialPath}\u0027 - asset_search type:tmat lists them\u0022 );\r\n\r\n        var index = materials.IndexOf( material );\r\n        if ( index \u003C 0 )\r\n        {\r\n            if ( materials.Count \u003E= MaxMaterials )\r\n                throw new Exception( $\u0022The terrain already has {MaxMaterials} materials, the most it can paint with - remove one with terrain_remove_material\u0022 );\r\n\r\n            materials.Add( material );\r\n            index = materials.Count - 1;\r\n            terrain.UpdateMaterialsBuffer();\r\n            AddUndo( session, terrain, \u0022Add Terrain Material\u0022, t =\u003E t.Storage.Materials.Remove( material ), t =\u003E t.Storage.Materials.Add( material ) );\r\n        }\r\n\r\n        return new { Id = terrain.GameObject.Id, Index = index, Name = material.ResourceName, MaterialCount = materials.Count };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Remove a material from a terrain\u0027s list. Later materials move down one index but painted texels\r\n    /// keep theirs, so texels of each later material now show the next one in the list, or nothing past\r\n    /// its end - repaint them with terrain_paint_material. The user can undo this.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022material\u0022\u003EThe material\u0027s index, name or asset path, as terrain_get_info lists them.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003ETerrain game object id. Empty means the scene\u0027s only terrain.\u003C/param\u003E\r\n    [McpTool( \u0022terrain_remove_material\u0022 )]\r\n    public static object RemoveMaterial( string material, string id = \u0022\u0022 )\r\n    {\r\n        var (terrain, session) = ForEdit( id );\r\n        var index = MaterialIndex( terrain, material );\r\n        var removed = terrain.Storage.Materials[index];\r\n\r\n        terrain.Storage.Materials.RemoveAt( index );\r\n        terrain.UpdateMaterialsBuffer();\r\n        AddUndo( session, terrain, \u0022Remove Terrain Material\u0022, t =\u003E t.Storage.Materials.Insert( index, removed ), t =\u003E t.Storage.Materials.RemoveAt( index ) );\r\n\r\n        return new { Id = terrain.GameObject.Id, RemovedIndex = index, RemovedName = removed?.ResourceName, MaterialCount = terrain.Storage.Materials.Count };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// The materials at a world position: the base and overlay material with their indices, the blend\r\n    /// between them (0 all base, 1 all overlay), which one dominates, and whether the spot is a hole.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003EWorld position as \u0027x,y,z\u0027. Only x and y matter.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003ETerrain game object id. Empty means the scene\u0027s only terrain.\u003C/param\u003E\r\n    [McpTool.ReadOnly( \u0022terrain_get_material_at\u0022 )]\r\n    public static object GetMaterialAt( Vector3 position, string id = \u0022\u0022 )\r\n    {\r\n        var terrain = ForRead( id );\r\n\r\n        // The engine accepts the far edge itself and reads one texel past the row there, so its bounds are checked here first\r\n        RequireTexel( terrain, position );\r\n        var info = terrain.GetMaterialAtWorldPosition( position )\r\n            ?? throw new Exception( $\u0022{position} is off the terrain \u0027{terrain.GameObject.Name}\u0027 - terrain_get_info shows its position and size\u0022 );\r\n\r\n        return new\r\n        {\r\n            Id = terrain.GameObject.Id,\r\n            BaseIndex = info.BaseTextureId,\r\n            BaseMaterial = info.BaseMaterial?.ResourceName,\r\n            OverlayIndex = info.OverlayTextureId,\r\n            OverlayMaterial = info.OverlayMaterial?.ResourceName,\r\n            Blend = MathF.Round( info.BlendFactor, 3 ),\r\n            Dominant = info.GetDominantMaterial()?.ResourceName,\r\n            info.IsHole\r\n        };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Paint one material solidly over a circle, replacing whatever base, overlay and blend were there.\r\n    /// Holes are kept. The user can undo this. Check with terrain_get_material_at.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003EBrush centre as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022material\u0022\u003EThe material\u0027s index, name or asset path, as terrain_get_info lists them. Only indices 0 to 31 can be painted.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022radius\u0022\u003EBrush radius in units.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003ETerrain game object id. Empty means the scene\u0027s only terrain.\u003C/param\u003E\r\n    [McpTool( \u0022terrain_paint_material\u0022 )]\r\n    public static object PaintMaterial( Vector3 position, string material, float radius = 50f, string id = \u0022\u0022 )\r\n    {\r\n        var (terrain, session) = ForEdit( id );\r\n        var index = PaintIndex( terrain, material );\r\n\r\n        var changed = EditControl( session, terrain, \u0022Terrain Paint\u0022, position, radius, c =\u003E new CompactTerrainMaterial( index, index, 0, c.IsHole ) );\r\n\r\n        return new { Id = terrain.GameObject.Id, Index = index, Name = terrain.Storage.Materials[index]?.ResourceName, TexelsChanged = changed };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Set a two-material blend over a circle: a base material, an overlay material and how much of the\r\n    /// overlay shows. Holes are kept. The user can undo this. Check with terrain_get_material_at.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003EBrush centre as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022baseIndex\u0022\u003EIndex of the base material, from terrain_get_info. Only indices 0 to 31 can be painted.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022overlayIndex\u0022\u003EIndex of the overlay material.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022blend\u0022\u003E0 shows only the base, 1 only the overlay.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022radius\u0022\u003EBrush radius in units.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003ETerrain game object id. Empty means the scene\u0027s only terrain.\u003C/param\u003E\r\n    [McpTool( \u0022terrain_blend_materials\u0022 )]\r\n    public static object BlendMaterials( Vector3 position, int baseIndex = 0, int overlayIndex = 1, [Sandbox.Range( 0, 1 )] float blend = 0.5f,\r\n        float radius = 50f, string id = \u0022\u0022 )\r\n    {\r\n        var (terrain, session) = ForEdit( id );\r\n        RequireFinite( \u0022blend\u0022, blend );\r\n        var b = PaintIndex( terrain, baseIndex.ToString() );\r\n        var o = PaintIndex( terrain, overlayIndex.ToString() );\r\n        var amount = (byte)Math.Clamp( (int)(blend * 255f), 0, 255 );\r\n\r\n        var changed = EditControl( session, terrain, \u0022Terrain Blend\u0022, position, radius, c =\u003E new CompactTerrainMaterial( b, o, amount, c.IsHole ) );\r\n\r\n        return new { Id = terrain.GameObject.Id, BaseIndex = b, OverlayIndex = o, Blend = amount / 255f, TexelsChanged = changed };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Cut a hole through the terrain over a circle, or fill one back in. Holes don\u0027t render and nothing\r\n    /// collides with them - use them for cave mouths and tunnels. Painted materials are kept. The user\r\n    /// can undo this.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003EBrush centre as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022radius\u0022\u003EBrush radius in units.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022enabled\u0022\u003ETrue cuts a hole, false fills it.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003ETerrain game object id. Empty means the scene\u0027s only terrain.\u003C/param\u003E\r\n    [McpTool( \u0022terrain_set_hole\u0022 )]\r\n    public static object SetHole( Vector3 position, float radius = 10f, bool enabled = true, string id = \u0022\u0022 )\r\n    {\r\n        var (terrain, session) = ForEdit( id );\r\n\r\n        var changed = EditControl( session, terrain, enabled ? \u0022Terrain Hole\u0022 : \u0022Terrain Fill Hole\u0022, position, radius, c =\u003E c with { IsHole = enabled } );\r\n\r\n        return new { Id = terrain.GameObject.Id, Hole = enabled, TexelsChanged = changed };\r\n    }\r\n\r\n    static int EditControl( SceneEditorSession session, Terrain terrain, string undoName, Vector3 position, float radius,\r\n        Func\u003CCompactTerrainMaterial, CompactTerrainMaterial\u003E change )\r\n    {\r\n        var map = terrain.Storage.ControlMap;\r\n        var brush = BrushAt( terrain, position, radius );\r\n\r\n        var changed = 0;\r\n        CommitControl( session, terrain, undoName, brush.Region,\r\n            () =\u003E changed = brush.ForEach( ( i, _, _, _ ) =\u003E map[i] = change( new CompactTerrainMaterial( map[i] ) ).Packed ) );\r\n\r\n        return changed;\r\n    }\r\n\r\n    // A list edited in the inspector can hold more materials than the control map can address; removing them stays allowed\r\n    static byte PaintIndex( Terrain terrain, string material )\r\n    {\r\n        var index = MaterialIndex( terrain, material );\r\n        return index \u003C MaxMaterials ? (byte)index\r\n            : throw new Exception( $\u0022Material {index} can\u0027t be painted - the control map stores 5-bit indices, so only the first {MaxMaterials} materials (0 to {MaxMaterials - 1}) can be painted; remove materials with terrain_remove_material to move it down\u0022 );\r\n    }\r\n\r\n    static int MaterialIndex( Terrain terrain, string material )\r\n    {\r\n        var materials = terrain.Storage.Materials;\r\n\r\n        if ( materials.Count == 0 )\r\n            throw new Exception( $\u0022\u0027{terrain.GameObject.Name}\u0027 has no materials yet - add one with terrain_add_material\u0022 );\r\n\r\n        if ( int.TryParse( material, out var index ) )\r\n        {\r\n            return index \u003E= 0 \u0026\u0026 index \u003C materials.Count ? index\r\n                : throw new Exception( $\u0022Material index {index} is out of range - \u0027{terrain.GameObject.Name}\u0027 has materials 0 to {materials.Count - 1}\u0022 );\r\n        }\r\n\r\n        bool Matches( string value ) =\u003E string.Equals( value, material, StringComparison.OrdinalIgnoreCase );\r\n\r\n        var found = materials.FindIndex( m =\u003E m is not null\r\n            \u0026\u0026 (Matches( m.ResourceName ) || Matches( m.ResourcePath ) || Matches( Path.GetFileNameWithoutExtension( m.ResourcePath ) )) );\r\n\r\n        return found \u003E= 0 ? found\r\n            : throw new Exception( $\u0022\u0027{material}\u0027 isn\u0027t one of the terrain\u0027s materials ({string.Join( \u0022, \u0022, materials.Select( ( m, i ) =\u003E $\u0022{i} {m?.ResourceName}\u0022 ) )}) - add it with terrain_add_material\u0022 );\r\n    }\r\n\r\n    // Material lists are small, so undo replays the list change itself; the terrain is resolved by id as in TerrainEdit.Commit\r\n    static void AddUndo( SceneEditorSession session, Terrain terrain, string name, Action\u003CTerrain\u003E undo, Action\u003CTerrain\u003E redo )\r\n    {\r\n        var scene = session.Scene;\r\n        var componentId = terrain.Id;\r\n\r\n        Action Apply( Action\u003CTerrain\u003E change ) =\u003E () =\u003E\r\n        {\r\n            if ( scene.Directory.FindComponentByGuid( componentId ) is not Terrain target || target.Storage is null )\r\n                return;\r\n\r\n            change( target );\r\n            target.UpdateMaterialsBuffer();\r\n        };\r\n\r\n        session.AddUndo( name, Apply( undo ), Apply( redo ) );\r\n        session.HasUnsavedChanges = true;\r\n    }\r\n}\r\n"},{"Ident":"arenula.leveltools","Path":"Editor/NavmeshTools.cs","FileName":"NavmeshTools.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":449884,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Diagnostics;\r\nusing System.Linq;\r\nusing System.Threading.Tasks;\r\nusing Editor;\r\nusing Editor.Mcp;\r\nusing Sandbox;\r\nusing Sandbox.Navigation;\r\nusing static LevelTools.McpHelpers;\r\n\r\nnamespace LevelTools;\r\n\r\n[McpToolset( \u0022navmesh\u0022, \u0022AI navigation - build the scene\u0027s navmesh, place NavMeshAgent, NavMeshArea and NavMeshLink components, generate or unload tiles, and test paths\u0022 )]\r\npublic static class NavmeshTools\r\n{\r\n    /// \u003Csummary\u003E\r\n    /// Add a NavMeshAgent - to an existing game object when id is given, otherwise to a new one. Unset\r\n    /// properties keep the component defaults. The user can undo this. Returns the game object and\r\n    /// component ids.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EGame object id to add the agent to, from scene_tree or find_game_objects. Empty creates a new object.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022name\u0022\u003EName for the new object. Ignored when id is given.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003EWorld position for the new object as \u0027x,y,z\u0027. Ignored when id is given.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022height\u0022\u003EAgent height in units.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022radius\u0022\u003EAgent radius in units.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022speed\u0022\u003EMaximum speed in units per second.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022acceleration\u0022\u003EMaximum acceleration. Match or exceed speed for snappy movement.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022updatePosition\u0022\u003EWhether the agent writes its simulated position back to the game object every frame.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022updateRotation\u0022\u003EWhether the agent turns the game object to face its movement.\u003C/param\u003E\r\n    [McpTool( \u0022navmesh_create_agent\u0022 )]\r\n    public static object CreateAgent( string id = \u0022\u0022, string name = \u0022NavMesh Agent\u0022, Vector3? position = null,\r\n        float? height = null, float? radius = null, float? speed = null, float? acceleration = null,\r\n        bool? updatePosition = null, bool? updateRotation = null )\r\n    {\r\n        var at = position ?? Vector3.Zero;\r\n        RequireFinite( \u0022position, height, radius, speed and acceleration\u0022, at.x, at.y, at.z, height ?? 0, radius ?? 0, speed ?? 0, acceleration ?? 0 );\r\n\r\n        var go = string.IsNullOrWhiteSpace( id ) ? null : FindByGuid( id );\r\n        var session = go is null ? ActiveSession() : SessionOf( go );\r\n\r\n        var undo = go is null\r\n            ? session.UndoScope( \u0022Create NavMesh Agent\u0022 ).WithGameObjectCreations()\r\n            : session.UndoScope( \u0022Add NavMeshAgent\u0022 ).WithComponentCreations();\r\n\r\n        using var sceneScope = session.Scene.Push();\r\n        using var undoScope = undo.Push();\r\n\r\n        if ( go is null )\r\n        {\r\n            go = session.Scene.CreateObject();\r\n            go.Name = name;\r\n            if ( position is { } p ) go.WorldPosition = p;\r\n        }\r\n\r\n        var agent = go.Components.Create\u003CNavMeshAgent\u003E();\r\n\r\n        if ( height is { } h ) agent.Height = h;\r\n        if ( radius is { } r ) agent.Radius = r;\r\n        if ( speed is { } s ) agent.MaxSpeed = s;\r\n        if ( acceleration is { } a ) agent.Acceleration = a;\r\n        if ( updatePosition is { } up ) agent.UpdatePosition = up;\r\n        if ( updateRotation is { } ur ) agent.UpdateRotation = ur;\r\n\r\n        return new { Id = go.Id, ComponentId = agent.Id, Name = go.Name, Speed = agent.MaxSpeed, Radius = agent.Radius };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Create a game object with a NavMeshArea - a box volume that blocks the navmesh (the default) or\r\n    /// marks it with an area definition. Run navmesh_generate afterwards to see the effect. The user\r\n    /// can undo this. Returns the new object\u0027s id.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003EWorld position of the box centre as \u0027x,y,z\u0027. Default origin.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022scale\u0022\u003EWorld scale of the object as \u0027x,y,z\u0027. The area\u0027s box is 100 units a side, so \u00272,2,1\u0027 covers 200x200x100.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022isBlocker\u0022\u003ETrue stops navmesh generation inside the box entirely.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022name\u0022\u003EName for the new object.\u003C/param\u003E\r\n    [McpTool( \u0022navmesh_create_area\u0022 )]\r\n    public static object CreateArea( Vector3? position = null, Vector3? scale = null, bool isBlocker = true, string name = \u0022NavMesh Area\u0022 )\r\n    {\r\n        Vector3 at = position ?? Vector3.Zero, size = scale ?? Vector3.One;\r\n        RequireFinite( \u0022position and scale\u0022, at.x, at.y, at.z, size.x, size.y, size.z );\r\n        var session = ActiveSession();\r\n\r\n        using var sceneScope = session.Scene.Push();\r\n        using var undoScope = session.UndoScope( \u0022Create NavMesh Area\u0022 ).WithGameObjectCreations().Push();\r\n\r\n        var go = session.Scene.CreateObject();\r\n        go.Name = name;\r\n        go.WorldPosition = position ?? Vector3.Zero;\r\n        if ( scale is { } sc ) go.WorldScale = sc;\r\n\r\n        var area = go.Components.Create\u003CNavMeshArea\u003E();\r\n        area.IsBlocker = isBlocker;\r\n\r\n        return new { Id = go.Id, Name = go.Name, Position = go.WorldPosition, IsBlocker = area.IsBlocker };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Create a game object with a NavMeshLink - an off-mesh connection such as a jump, drop or ladder\r\n    /// between two points near the navmesh. The object sits at the midpoint. The user can undo this.\r\n    /// Returns the new object\u0027s id.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022start\u0022\u003ELink start in world space as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022end\u0022\u003ELink end in world space as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022bidirectional\u0022\u003EWhether agents can traverse end to start too. Unset keeps the component default.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022name\u0022\u003EName for the new object.\u003C/param\u003E\r\n    [McpTool( \u0022navmesh_create_link\u0022 )]\r\n    public static object CreateLink( Vector3 start, Vector3 end, bool? bidirectional = null, string name = \u0022NavMesh Link\u0022 )\r\n    {\r\n        RequireFinite( \u0022start and end\u0022, start.x, start.y, start.z, end.x, end.y, end.z );\r\n        var session = ActiveSession();\r\n        var midpoint = (start \u002B end) / 2f;\r\n\r\n        using var sceneScope = session.Scene.Push();\r\n        using var undoScope = session.UndoScope( \u0022Create NavMesh Link\u0022 ).WithGameObjectCreations().Push();\r\n\r\n        var go = session.Scene.CreateObject();\r\n        go.Name = name;\r\n        go.WorldPosition = midpoint;\r\n\r\n        var link = go.Components.Create\u003CNavMeshLink\u003E();\r\n        link.LocalStartPosition = start - midpoint;\r\n        link.LocalEndPosition = end - midpoint;\r\n        if ( bidirectional is { } bd ) link.IsBiDirectional = bd;\r\n\r\n        return new { Id = go.Id, Name = go.Name, Position = go.WorldPosition, Start = start, End = end, Bidirectional = link.IsBiDirectional };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Build the active scene\u0027s whole navmesh from its static and keyframed colliders and wait for it to\r\n    /// finish. Turns the scene\u0027s navmesh on if it was off and marks the scene unsaved, since that setting saves with it. Not\r\n    /// undoable; a rebuild replaces the previous mesh. Saving the scene in the editor bakes it to\r\n    /// navmesh/baked.navdata in the scene\u0027s folder, so it loads without rebuilding. Check the outcome\r\n    /// with navmesh_get_status or navmesh_query_path.\r\n    /// \u003C/summary\u003E\r\n    [McpTool( \u0022navmesh_generate\u0022 )]\r\n    public static async Task\u003Cobject\u003E Generate()\r\n    {\r\n        var session = ActiveSession();\r\n        var scene = session.Scene;\r\n        var navMesh = scene.NavMesh;\r\n\r\n        if ( navMesh.IsGenerating )\r\n            throw new Exception( \u0022The navmesh is already generating - wait a moment and check navmesh_get_status\u0022 );\r\n\r\n        var timer = Stopwatch.StartNew();\r\n        var wasEnabled = navMesh.IsEnabled;\r\n\r\n        // Generate computes Bounds synchronously before its first await, so they are read here on the main thread\r\n        var generating = navMesh.Generate( scene.PhysicsWorld );\r\n        var bounds = navMesh.Bounds;\r\n\r\n        // IsEnabled saves with the scene, and only baking would otherwise mark it changed\r\n        if ( !wasEnabled \u0026\u0026 navMesh.IsEnabled )\r\n            session.HasUnsavedChanges = true;\r\n\r\n        // IsGenerating was refused above, so false here means a tile failed to build\r\n        if ( !await generating )\r\n            throw new Exception( \u0022Some navmesh tiles failed to build - the rest were built; test the areas that matter with navmesh_query_path\u0022 );\r\n\r\n        return new\r\n        {\r\n            Generated = true,\r\n            GenerationTimeMs = timer.ElapsedMilliseconds,\r\n            Bounds = new { Mins = bounds.Mins, Maxs = bounds.Maxs }\r\n        };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Queue navmesh tiles for rebuilding over the next frames - the tile at a position, or every tile\r\n    /// overlapping a box. For open worlds with deferred generation (navmesh_set_defer_generation). Returns\r\n    /// at once; not undoable. Needs the scene\u0027s navmesh on - navmesh_get_status shows IsEnabled.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003EA world position inside the tile as \u0027x,y,z\u0027. Used when the bounds are empty.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022boundsMin\u0022\u003EBox minimum corner as \u0027x,y,z\u0027. Give with boundsMax instead of position.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022boundsMax\u0022\u003EBox maximum corner as \u0027x,y,z\u0027. Give with boundsMin instead of position.\u003C/param\u003E\r\n    [McpTool( \u0022navmesh_generate_tile\u0022 )]\r\n    public static string GenerateTile( Vector3? position = null, Vector3? boundsMin = null, Vector3? boundsMax = null )\r\n    {\r\n        var navMesh = EnabledNavMesh();\r\n\r\n        if ( TileBounds( position, boundsMin, boundsMax ) is { } box )\r\n        {\r\n            navMesh.RequestTilesGeneration( box );\r\n            return $\u0022Queued navmesh tiles overlapping {box.Mins} to {box.Maxs} for generation\u0022;\r\n        }\r\n\r\n        navMesh.RequestTileGeneration( position.Value );\r\n        return $\u0022Queued the navmesh tile at {position.Value} for generation\u0022;\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Remove navmesh tiles - the tile at a position, or every tile overlapping a box - to free memory in\r\n    /// open worlds. Agents can no longer path there until navmesh_generate_tile rebuilds them. Not\r\n    /// undoable. Needs the scene\u0027s navmesh on.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003EA world position inside the tile as \u0027x,y,z\u0027. Used when the bounds are empty.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022boundsMin\u0022\u003EBox minimum corner as \u0027x,y,z\u0027. Give with boundsMax instead of position.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022boundsMax\u0022\u003EBox maximum corner as \u0027x,y,z\u0027. Give with boundsMin instead of position.\u003C/param\u003E\r\n    [McpTool( \u0022navmesh_unload_tile\u0022 )]\r\n    public static string UnloadTile( Vector3? position = null, Vector3? boundsMin = null, Vector3? boundsMax = null )\r\n    {\r\n        var navMesh = EnabledNavMesh();\r\n\r\n        if ( TileBounds( position, boundsMin, boundsMax ) is { } box )\r\n        {\r\n            navMesh.UnloadTiles( box );\r\n            return $\u0022Unloaded navmesh tiles overlapping {box.Mins} to {box.Maxs}\u0022;\r\n        }\r\n\r\n        navMesh.UnloadTile( position.Value );\r\n        return $\u0022Unloaded the navmesh tile at {position.Value}\u0022;\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Turn deferred navmesh generation on or off for the active scene. When on, loading the scene builds\r\n    /// no tiles and baked data is ignored - generate them on demand with navmesh_generate_tile. Saves with\r\n    /// the scene. The user can undo this.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022enabled\u0022\u003ETrue to defer tile generation, false to build every tile on load.\u003C/param\u003E\r\n    [McpTool( \u0022navmesh_set_defer_generation\u0022 )]\r\n    public static string SetDeferGeneration( bool enabled = true )\r\n    {\r\n        var session = ActiveSession();\r\n        var navMesh = session.Scene.NavMesh;\r\n        var previous = navMesh.DeferGeneration;\r\n\r\n        navMesh.DeferGeneration = enabled;\r\n        session.AddUndo( \u0022NavMesh Defer Generation\u0022, () =\u003E navMesh.DeferGeneration = previous, () =\u003E navMesh.DeferGeneration = enabled );\r\n        session.HasUnsavedChanges = true;\r\n\r\n        return enabled\r\n            ? \u0022Deferred generation on - tiles won\u0027t build on load; use navmesh_generate_tile\u0022\r\n            : \u0022Deferred generation off - every tile builds on load\u0022;\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// The navigation state of the active scene - whether the navmesh is on, generating or dirty, deferred\r\n    /// generation, its agent settings and bounds, and the NavMeshAgent, NavMeshArea and NavMeshLink\r\n    /// counts, disabled components included. Lists the agents with their game object ids and whether each\r\n    /// is enabled.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022limit\u0022\u003EHow many agents to list. Default 100, max 1000. AgentCount is always the full count.\u003C/param\u003E\r\n    [McpTool.ReadOnly( \u0022navmesh_get_status\u0022 )]\r\n    public static object GetStatus( [Sandbox.Range( 0, 1000 )] int limit = 100 )\r\n    {\r\n        var scene = ReadScene();\r\n        var navMesh = scene.NavMesh;\r\n        var agents = scene.Components.GetAll\u003CNavMeshAgent\u003E( FindMode.EverythingInDescendants ).ToList();\r\n\r\n        return new\r\n        {\r\n            Scene = scene.Name,\r\n            IsEnabled = navMesh.IsEnabled,\r\n            IsGenerating = navMesh.IsGenerating,\r\n            IsDirty = navMesh.IsDirty,\r\n            DeferGeneration = navMesh.DeferGeneration,\r\n            AgentHeight = navMesh.AgentHeight,\r\n            AgentRadius = navMesh.AgentRadius,\r\n            AgentStepSize = navMesh.AgentStepSize,\r\n            AgentMaxSlope = navMesh.AgentMaxSlope,\r\n            Bounds = new { Mins = navMesh.Bounds.Mins, Maxs = navMesh.Bounds.Maxs },\r\n            AgentCount = agents.Count,\r\n            AreaCount = scene.Components.GetAll\u003CNavMeshArea\u003E( FindMode.EverythingInDescendants ).Count(),\r\n            LinkCount = scene.Components.GetAll\u003CNavMeshLink\u003E( FindMode.EverythingInDescendants ).Count(),\r\n            Agents = agents.Take( limit ).Select( a =\u003E new { Id = a.GameObject.Id, Name = a.GameObject.Name, Enabled = a.Active, Speed = a.MaxSpeed, Position = a.GameObject.WorldPosition } ).ToArray()\r\n        };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Find a path across the active scene\u0027s navmesh between two points, as an agent would walk it. Both\r\n    /// points should be on or near walkable ground. Returns the waypoints, total distance and whether the\r\n    /// path is Complete or only Partial (ends at the closest reachable spot). Run navmesh_generate first.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022from\u0022\u003EPath start as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022to\u0022\u003EPath end as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    [McpTool.ReadOnly( \u0022navmesh_query_path\u0022 )]\r\n    public static object QueryPath( Vector3 from, Vector3 to )\r\n    {\r\n        var navMesh = ReadScene().NavMesh;\r\n\r\n        if ( !navMesh.IsEnabled )\r\n            throw new Exception( \u0022The scene\u0027s navmesh is off - build it with navmesh_generate first\u0022 );\r\n\r\n        var path = navMesh.CalculatePath( new CalculatePathRequest { Start = from, Target = to } );\r\n\r\n        if ( !path.IsValid )\r\n        {\r\n            throw new Exception( path.Status switch\r\n            {\r\n                NavMeshPathStatus.StartNotFound =\u003E $\u0022No navmesh near the start {from} - pick a point on walkable ground, or rebuild with navmesh_generate\u0022,\r\n                NavMeshPathStatus.TargetNotFound =\u003E $\u0022No navmesh near the target {to} - pick a point on walkable ground, or rebuild with navmesh_generate\u0022,\r\n                _ =\u003E $\u0022No path between {from} and {to} ({path.Status}) - they may be on disconnected parts of the navmesh\u0022\r\n            } );\r\n        }\r\n\r\n        var points = path.Points.Select( p =\u003E p.Position ).ToArray();\r\n        var distance = 0f;\r\n        for ( int i = 1; i \u003C points.Length; i\u002B\u002B )\r\n            distance \u002B= points[i - 1].Distance( points[i] );\r\n\r\n        return new { Status = path.Status.ToString(), WaypointCount = points.Length, Distance = MathF.Round( distance, 1 ), Waypoints = points };\r\n    }\r\n\r\n    private static NavMesh EnabledNavMesh()\r\n    {\r\n        var navMesh = ActiveSession().Scene.NavMesh;\r\n\r\n        if ( !navMesh.IsEnabled )\r\n            throw new Exception( \u0022The scene\u0027s navmesh is off, so tile calls would do nothing - turn it on with navmesh_generate or in the scene\u0027s NavMesh settings\u0022 );\r\n\r\n        return navMesh;\r\n    }\r\n\r\n    // Null means \u0022use position\u0022; throws when neither a full box nor a position was given\r\n    private static BBox? TileBounds( Vector3? position, Vector3? boundsMin, Vector3? boundsMax )\r\n    {\r\n        foreach ( var v in new[] { position, boundsMin, boundsMax } )\r\n            if ( v is { } given ) RequireFinite( \u0022position and bounds\u0022, given.x, given.y, given.z );\r\n\r\n        if ( boundsMin is { } min \u0026\u0026 boundsMax is { } max )\r\n            return new BBox( min, max );\r\n\r\n        if ( boundsMin is not null || boundsMax is not null )\r\n            throw new Exception( \u0022Give both boundsMin and boundsMax, or just position\u0022 );\r\n\r\n        if ( position is null )\r\n            throw new Exception( \u0022Give position (\u0027x,y,z\u0027), or boundsMin and boundsMax, for the tiles\u0022 );\r\n\r\n        return null;\r\n    }\r\n}\r\n"},{"Ident":"arenula.leveltools","Path":"Editor/ProjectTools.cs","FileName":"ProjectTools.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":449884,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing Editor;\r\nusing Editor.Mcp;\r\nusing Sandbox;\r\nusing Sandbox.Physics;\r\n\r\nnamespace LevelTools;\r\n\r\n[McpToolset( \u0022project\u0022, \u0022Project settings an agent cannot reach cleanly elsewhere - the physics collision rule matrix\u0022 )]\r\npublic static class ProjectTools\r\n{\r\n    /// \u003Csummary\u003E\r\n    /// Read the project\u0027s collision rules: each tag\u0027s default result and every tag pair\u0027s explicit result.\r\n    /// A pair\u0027s rule wins over the defaults; with no pair, the less colliding of the two defaults applies,\r\n    /// and Unset means Collide. Give two tags to also get the Effective result between them.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022tagA\u0022\u003EFirst tag, for the Effective result. Optional.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022tagB\u0022\u003ESecond tag, for the Effective result. Optional.\u003C/param\u003E\r\n    [McpTool.ReadOnly( \u0022project_get_collision\u0022 )]\r\n    public static object GetCollision( string tagA = \u0022\u0022, string tagB = \u0022\u0022 )\r\n    {\r\n        var rules = ProjectSettings.Collision;\r\n\r\n        var defaults = rules.Defaults.OrderBy( x =\u003E x.Key, StringComparer.OrdinalIgnoreCase )\r\n            .Select( x =\u003E new { Tag = x.Key, Result = x.Value.ToString() } ).ToList();\r\n        var pairs = rules.Pairs.Where( x =\u003E x.Value != CollisionRules.Result.Unset )\r\n            .OrderBy( x =\u003E x.Key.Left, StringComparer.OrdinalIgnoreCase ).ThenBy( x =\u003E x.Key.Right, StringComparer.OrdinalIgnoreCase )\r\n            .Select( x =\u003E new { A = x.Key.Left, B = x.Key.Right, Result = x.Value.ToString() } ).ToList();\r\n        var tags = rules.Tags.OrderBy( x =\u003E x, StringComparer.OrdinalIgnoreCase ).ToList();\r\n\r\n        if ( string.IsNullOrWhiteSpace( tagA ) || string.IsNullOrWhiteSpace( tagB ) )\r\n            return new { Defaults = defaults, Pairs = pairs, Tags = tags };\r\n\r\n        var effective = rules.GetCollisionRule( Tag( tagA ), Tag( tagB ) ).ToString();\r\n        return new { Defaults = defaults, Pairs = pairs, Tags = tags, Effective = effective };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Set a collision rule and save it to ProjectSettings/Collision.config immediately. With tagB, sets the\r\n    /// rule for that pair of tags (order doesn\u0027t matter); without it, sets tagA\u0027s default. Unset removes the\r\n    /// entry. Tags are lowercased and trimmed. The user cannot undo this - to undo it, set the returned\r\n    /// Before value back.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022tagA\u0022\u003EA tag, e.g. \u0027player\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022result\u0022\u003ECollide, Trigger (no collision, but touch callbacks), Ignore, or Unset to remove the entry.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022tagB\u0022\u003ESecond tag for a pair rule. Empty sets tagA\u0027s default.\u003C/param\u003E\r\n    [McpTool( \u0022project_set_collision_rule\u0022 )]\r\n    public static object SetCollisionRule( string tagA, CollisionRules.Result result, string tagB = \u0022\u0022 )\r\n    {\r\n        var rules = ProjectSettings.Collision;\r\n        var a = Tag( tagA );\r\n        var isPair = !string.IsNullOrWhiteSpace( tagB );\r\n        var b = isPair ? Tag( tagB ) : null;\r\n\r\n        CollisionRules.Result before;\r\n\r\n        if ( isPair )\r\n        {\r\n            CollisionRules.Pair key = (a, b);\r\n            before = rules.Pairs.GetValueOrDefault( key );\r\n\r\n            if ( result == CollisionRules.Result.Unset ) rules.Pairs.Remove( key );\r\n            else rules.Pairs[key] = result;\r\n        }\r\n        else\r\n        {\r\n            // Defaults is case-sensitive: fold any differently-cased entry into the lowercase one\r\n            var existing = rules.Defaults.Keys.Where( k =\u003E string.Equals( k, a, StringComparison.OrdinalIgnoreCase ) ).ToList();\r\n            before = existing.Count \u003E 0 ? rules.Defaults[existing[0]] : CollisionRules.Result.Unset;\r\n\r\n            foreach ( var k in existing ) rules.Defaults.Remove( k );\r\n            if ( result != CollisionRules.Result.Unset ) rules.Defaults[a] = result;\r\n        }\r\n\r\n        EditorUtility.SaveProjectSettings( rules, \u0022Collision.config\u0022 );\r\n\r\n        if ( !isPair )\r\n            return new { Key = a, Before = before.ToString(), After = result.ToString() };\r\n\r\n        return new { Key = $\u0022{a}, {b}\u0022, Before = before.ToString(), After = result.ToString(), Effective = rules.GetCollisionRule( a, b ).ToString() };\r\n    }\r\n\r\n    // Tags are lowercase in the engine, but the rule dictionaries compare as given\r\n    static string Tag( string tag )\r\n    {\r\n        var t = (tag ?? \u0022\u0022).Trim().ToLowerInvariant();\r\n\r\n        if ( t.Length == 0 )\r\n            throw new Exception( \u0022Give a tag, e.g. \u0027player\u0027\u0022 );\r\n        if ( t.Any( char.IsWhiteSpace ) )\r\n            throw new Exception( $\u0022\u0027{tag}\u0027 has whitespace inside it - a tag is one word, e.g. \u0027player_clip\u0027\u0022 );\r\n\r\n        return t;\r\n    }\r\n}\r\n"},{"Ident":"arenula.leveltools","Path":"Editor/TerrainSculptTools.cs","FileName":"TerrainSculptTools.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":449884,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing Editor;\r\nusing Editor.Mcp;\r\nusing Sandbox;\r\nusing Sandbox.Clutter;\r\nusing static LevelTools.McpHelpers;\r\nusing static LevelTools.TerrainEdit;\r\n\r\nnamespace LevelTools;\r\n\r\n[McpToolset( \u0022terrain\u0022 )]\r\npublic static class TerrainSculptTools\r\n{\r\n    public enum NoiseType { Perlin, Ridged, Billow }\r\n\r\n    public enum NoiseMode { Set, Add, Multiply }\r\n\r\n    public enum StampShape { Hill, Crater, Mesa, Ridge, Valley, Plateau }\r\n\r\n    public enum StampMode { Add, Subtract, Set }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Fill the whole heightmap with fractal Perlin noise. Set replaces heights with noise times\r\n    /// amplitude, Add adds that on top, Multiply scales existing heights by the 0 to 1 noise value.\r\n    /// Ridged makes sharp crests, Billow rounded bumps. The same seed and settings give the same result.\r\n    /// The user can undo this. Returns the new height range; follow with terrain_erode for realism.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022type\u0022\u003ENoise shape.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022scale\u0022\u003ENoise frequency per heightmap texel. Smaller gives broader features.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022amplitude\u0022\u003EHeight of the noise in units. Default 30% of the terrain\u0027s maximum height.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022octaves\u0022\u003EDetail layers, 1 to 12.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022persistence\u0022\u003EHow much each octave\u0027s amplitude shrinks, 0 to 1.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022lacunarity\u0022\u003EHow much each octave\u0027s frequency grows.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022seed\u0022\u003ERandom seed.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022mode\u0022\u003EHow noise combines with the existing heights.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022offsetX\u0022\u003ENoise offset in texels along X, to move the pattern.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022offsetY\u0022\u003ENoise offset in texels along Y.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003ETerrain game object id. Empty means the scene\u0027s only terrain.\u003C/param\u003E\r\n    [McpTool( \u0022terrain_noise\u0022 )]\r\n    public static object Noise( NoiseType type = NoiseType.Perlin, float scale = 0.01f, float? amplitude = null, [Sandbox.Range( 1, 12 )] int octaves = 4,\r\n        float persistence = 0.5f, float lacunarity = 2f, int seed = 42, NoiseMode mode = NoiseMode.Set, float offsetX = 0f, float offsetY = 0f, string id = \u0022\u0022 )\r\n    {\r\n        var (terrain, session) = ForEdit( id );\r\n        var map = terrain.Storage.HeightMap;\r\n        var res = terrain.Storage.Resolution;\r\n        var amp = amplitude ?? terrain.Storage.TerrainHeight * 0.3f;\r\n        RequireFinite( \u0022scale, amplitude, persistence, lacunarity and offsets\u0022, scale, amp, persistence, lacunarity, offsetX, offsetY );\r\n        var perm = Permutation( seed );\r\n\r\n        CommitHeights( session, terrain, \u0022Terrain Noise\u0022, Whole( terrain ), () =\u003E\r\n        {\r\n            for ( var y = 0; y \u003C res; y\u002B\u002B )\r\n            {\r\n                for ( var x = 0; x \u003C res; x\u002B\u002B )\r\n                {\r\n                    var n = Fbm( (x \u002B offsetX) * scale, (y \u002B offsetY) * scale, octaves, persistence, lacunarity, perm );\r\n                    if ( type == NoiseType.Ridged ) n = 1f - MathF.Abs( n * 2f - 1f );\r\n                    else if ( type == NoiseType.Billow ) n = MathF.Abs( n * 2f - 1f );\r\n\r\n                    var i = y * res \u002B x;\r\n                    var current = HeightOf( terrain, map[i] );\r\n                    map[i] = RawOf( terrain, mode switch\r\n                    {\r\n                        NoiseMode.Add =\u003E current \u002B n * amp,\r\n                        NoiseMode.Multiply =\u003E current * n,\r\n                        _ =\u003E n * amp\r\n                    } );\r\n                }\r\n            }\r\n        } );\r\n\r\n        return new { Id = terrain.GameObject.Id, Type = type.ToString(), Mode = mode.ToString(), LowestHeight = HeightOf( terrain, map.Min() ), HighestHeight = HeightOf( terrain, map.Max() ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Hydraulic erosion over the whole heightmap: simulated water droplets carve channels and deposit\r\n    /// sediment downhill (Hans Theobald Beyer\u0027s particle method). Runs on the editor thread - 50000\r\n    /// droplets on a 512 terrain takes about a second. The user can undo this.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022iterations\u0022\u003ENumber of droplets, up to 1000000.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022erosionRate\u0022\u003EHow fast droplets pick up sediment, 0 to 1.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022depositionRate\u0022\u003EHow fast they drop excess sediment, 0 to 1.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022evaporationRate\u0022\u003EWater lost per step, 0 to 1.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022gravity\u0022\u003EDownhill acceleration.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022inertia\u0022\u003EHow much a droplet keeps its direction, 0 to 1.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022capacity\u0022\u003ESediment a droplet can carry, relative to its speed, water and slope.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022minCapacity\u0022\u003ELeast sediment capacity, so droplets on flat ground still erode.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022lifetime\u0022\u003EMost steps a droplet lives.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022erosionRadius\u0022\u003ERadius in texels that each erosion step spreads over.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022seed\u0022\u003ERandom seed for droplet starting points.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003ETerrain game object id. Empty means the scene\u0027s only terrain.\u003C/param\u003E\r\n    [McpTool( \u0022terrain_erode\u0022 )]\r\n    public static object Erode( [Sandbox.Range( 1, 1000000 )] int iterations = 50000, float erosionRate = 0.3f, float depositionRate = 0.3f,\r\n        float evaporationRate = 0.01f, float gravity = 4f, float inertia = 0.05f, float capacity = 4f, float minCapacity = 0.01f,\r\n        [Sandbox.Range( 1, 200 )] int lifetime = 30, [Sandbox.Range( 1, 16 )] int erosionRadius = 3, int seed = 42, string id = \u0022\u0022 )\r\n    {\r\n        RequireFinite( \u0022the erosion rates, gravity, inertia and capacities\u0022, erosionRate, depositionRate, evaporationRate, gravity, inertia, capacity, minCapacity );\r\n        var (terrain, session) = ForEdit( id );\r\n        var res = terrain.Storage.Resolution;\r\n        var map = terrain.Storage.HeightMap;\r\n\r\n        CommitHeights( session, terrain, \u0022Terrain Erode\u0022, Whole( terrain ), () =\u003E\r\n        {\r\n            // Normalised floats, so small per-step changes aren\u0027t lost to 16-bit rounding\r\n            var h = map.Select( x =\u003E x / (float)ushort.MaxValue ).ToArray();\r\n            var brush = ErosionBrush( erosionRadius );\r\n            var rng = new Random( seed );\r\n\r\n            for ( var drop = 0; drop \u003C iterations; drop\u002B\u002B )\r\n            {\r\n                float px = rng.NextSingle() * (res - 2) \u002B 1, py = rng.NextSingle() * (res - 2) \u002B 1;\r\n                float dx = 0, dy = 0, speed = 1, water = 1, sediment = 0;\r\n\r\n                for ( var life = 0; life \u003C lifetime; life\u002B\u002B )\r\n                {\r\n                    int nx = (int)px, ny = (int)py;\r\n                    if ( nx \u003C 1 || nx \u003E= res - 1 || ny \u003C 1 || ny \u003E= res - 1 ) break;\r\n\r\n                    float cx = px - nx, cy = py - ny;\r\n                    var i = ny * res \u002B nx;\r\n                    float nw = h[i], ne = h[i \u002B 1], sw = h[i \u002B res], se = h[i \u002B res \u002B 1];\r\n\r\n                    var gx = (ne - nw) * (1 - cy) \u002B (se - sw) * cy;\r\n                    var gy = (sw - nw) * (1 - cx) \u002B (se - ne) * cx;\r\n                    var height = nw * (1 - cx) * (1 - cy) \u002B ne * cx * (1 - cy) \u002B sw * (1 - cx) * cy \u002B se * cx * cy;\r\n\r\n                    dx = dx * inertia - gx * (1 - inertia);\r\n                    dy = dy * inertia - gy * (1 - inertia);\r\n                    var len = MathF.Sqrt( dx * dx \u002B dy * dy );\r\n                    if ( len \u003E 0 ) { dx /= len; dy /= len; }\r\n                    else { dx = rng.NextSingle() * 2 - 1; dy = rng.NextSingle() * 2 - 1; }\r\n\r\n                    float npx = px \u002B dx, npy = py \u002B dy;\r\n                    if ( npx \u003C 1 || npx \u003E= res - 1 || npy \u003C 1 || npy \u003E= res - 1 ) break;\r\n\r\n                    var dh = Bilinear( h, res, npx, npy ) - height;\r\n                    var cap = Math.Max( -dh * speed * water * capacity, minCapacity );\r\n\r\n                    if ( sediment \u003E cap || dh \u003E 0 )\r\n                    {\r\n                        var deposit = dh \u003E 0 ? Math.Min( dh, sediment ) : (sediment - cap) * depositionRate;\r\n                        sediment -= deposit;\r\n                        h[i] \u002B= deposit * (1 - cx) * (1 - cy);\r\n                        h[i \u002B 1] \u002B= deposit * cx * (1 - cy);\r\n                        h[i \u002B res] \u002B= deposit * (1 - cx) * cy;\r\n                        h[i \u002B res \u002B 1] \u002B= deposit * cx * cy;\r\n                    }\r\n                    else\r\n                    {\r\n                        var erode = Math.Min( (cap - sediment) * erosionRate, -dh );\r\n                        foreach ( var (bx, by, w) in brush )\r\n                        {\r\n                            int ex = nx \u002B bx, ey = ny \u002B by;\r\n                            if ( ex \u003C 0 || ex \u003E= res || ey \u003C 0 || ey \u003E= res ) continue;\r\n                            h[ey * res \u002B ex] = Math.Max( 0, h[ey * res \u002B ex] - erode * w );\r\n                        }\r\n                        sediment \u002B= erode;\r\n                    }\r\n\r\n                    speed = MathF.Sqrt( Math.Max( 0, speed * speed \u002B dh * gravity ) );\r\n                    water *= 1 - evaporationRate;\r\n                    px = npx; py = npy;\r\n                    if ( water \u003C 0.001f ) break;\r\n                }\r\n            }\r\n\r\n            for ( var i = 0; i \u003C map.Length; i\u002B\u002B )\r\n                map[i] = (ushort)MathF.Round( Math.Clamp( h[i], 0f, 1f ) * ushort.MaxValue );\r\n        } );\r\n\r\n        return new { Id = terrain.GameObject.Id, Droplets = iterations, LowestHeight = HeightOf( terrain, map.Min() ), HighestHeight = HeightOf( terrain, map.Max() ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Press a landform into the heightmap: a Gaussian Hill, a Crater with a rim, a flat-topped Mesa or\r\n    /// Plateau, or a Ridge or Valley line turned by angle. Crater, Ridge and Valley fade to zero over\r\n    /// the outer fifth of the radius, so no shape ends in a wall at its edge. Add raises by the shape, Subtract lowers by it,\r\n    /// Set replaces heights with it. The user can undo this. Check with terrain_get_height_region.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003ECentre of the stamp as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022shape\u0022\u003ELandform to stamp.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022mode\u0022\u003EHow the shape combines with existing heights.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022height\u0022\u003EPeak height of the shape in units.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022radius\u0022\u003EStamp radius in units.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022angle\u0022\u003EDirection of a Ridge or Valley in degrees: 0 runs it along X, 90 along Y.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003ETerrain game object id. Empty means the scene\u0027s only terrain.\u003C/param\u003E\r\n    [McpTool( \u0022terrain_stamp\u0022 )]\r\n    public static object Stamp( Vector3 position, StampShape shape = StampShape.Hill, StampMode mode = StampMode.Add, float height = 20f,\r\n        float radius = 50f, float angle = 0f, string id = \u0022\u0022 )\r\n    {\r\n        RequireFinite( \u0022height and angle\u0022, height, angle );\r\n        var (terrain, session) = ForEdit( id );\r\n        var map = terrain.Storage.HeightMap;\r\n        var brush = BrushAt( terrain, position, radius );\r\n        var r = (float)brush.Radius;\r\n        var sigma = r / 3f;\r\n        float cos = MathF.Cos( angle.DegreeToRadian() ), sin = MathF.Sin( angle.DegreeToRadian() );\r\n\r\n        var changed = 0;\r\n        CommitHeights( session, terrain, $\u0022Terrain Stamp {shape}\u0022, brush.Region, () =\u003E changed = brush.ForEach( ( i, dx, dy, t ) =\u003E\r\n        {\r\n            var dist = t * r;\r\n            var across = -dx * sin \u002B dy * cos;\r\n\r\n            // These shapes are still well above zero at the radius, so they fade out over its outer fifth instead of ending in a wall\r\n            var edgeFade = SmoothStep( Math.Clamp( (1f - t) / 0.2f, 0f, 1f ) );\r\n\r\n            var profile = shape switch\r\n            {\r\n                StampShape.Crater =\u003E (-Gauss( dist, sigma ) \u002B 0.6f * Gauss( dist - r * 0.8f, r * 0.15f )) * edgeFade,\r\n                StampShape.Mesa =\u003E SmoothStep( t \u003C 0.7f ? 1f : 1f - (t - 0.7f) / 0.3f ),\r\n                StampShape.Ridge =\u003E Gauss( across, sigma * MathF.Sqrt( 0.3f ) ) * edgeFade,\r\n                StampShape.Valley =\u003E -Gauss( across, sigma * MathF.Sqrt( 0.3f ) ) * edgeFade,\r\n                StampShape.Plateau =\u003E t \u003C 0.6f ? 1f : Math.Max( 0f, 1f - (t - 0.6f) / 0.4f ),\r\n                _ =\u003E Gauss( dist, sigma )\r\n            };\r\n\r\n            var current = HeightOf( terrain, map[i] );\r\n            map[i] = RawOf( terrain, mode switch\r\n            {\r\n                StampMode.Set =\u003E height * profile,\r\n                StampMode.Subtract =\u003E current - height * MathF.Abs( profile ),\r\n                _ =\u003E current \u002B height * profile\r\n            } );\r\n        } ) );\r\n\r\n        return new { Id = terrain.GameObject.Id, Shape = shape.ToString(), Mode = mode.ToString(), TexelsChanged = changed };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Regenerate the objects a ClutterComponent scatters. Volume mode rebuilds everything inside its\r\n    /// Bounds; Infinite mode rebuilds the streamed tiles overlapping the box, or every tile when no box is\r\n    /// given, and they stream back in around the camera. Either fills in over the next frames. Set the\r\n    /// component\u0027s Clutter definition, Seed or Mode with set_component first. Not undoable - generation\r\n    /// finishes after the call returns; the same seed scatters the same objects again.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EId of the game object with the ClutterComponent.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022boundsMin\u0022\u003EInfinite mode only: box minimum corner as \u0027x,y,z\u0027. Give with boundsMax.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022boundsMax\u0022\u003EInfinite mode only: box maximum corner as \u0027x,y,z\u0027. Give with boundsMin.\u003C/param\u003E\r\n    [McpTool( \u0022terrain_regenerate_clutter\u0022 )]\r\n    public static string RegenerateClutter( string id, Vector3? boundsMin = null, Vector3? boundsMax = null )\r\n    {\r\n        var clutter = FindClutter( id );\r\n        var name = clutter.GameObject.Name;\r\n\r\n        if ( clutter.Clutter is null )\r\n            throw new Exception( $\u0022\u0027{name}\u0027 has no clutter definition - set its Clutter property to a .clutter asset with set_component\u0022 );\r\n\r\n        if ( (boundsMin is null) != (boundsMax is null) )\r\n            throw new Exception( \u0022Give both boundsMin and boundsMax, or neither\u0022 );\r\n\r\n        if ( !clutter.Infinite )\r\n        {\r\n            if ( boundsMin is not null )\r\n                throw new Exception( $\u0022\u0027{name}\u0027 is in Volume mode, which always regenerates its whole Bounds - change Bounds with set_component, or call without a box\u0022 );\r\n\r\n            clutter.Generate();\r\n            SessionOf( clutter.GameObject ).HasUnsavedChanges = true;\r\n            return $\u0022Regenerating the clutter inside \u0027{name}\u0027\u0027s bounds - it fills in over the next frames\u0022;\r\n        }\r\n\r\n        if ( boundsMin is { } min \u0026\u0026 boundsMax is { } max )\r\n        {\r\n            clutter.InvalidateTilesInBounds( new BBox( min, max ) );\r\n            return $\u0022Regenerating \u0027{name}\u0027\u0027s clutter tiles overlapping {min} to {max}\u0022;\r\n        }\r\n\r\n        clutter.ClearInfinite();\r\n        return $\u0022Cleared every clutter tile of \u0027{name}\u0027 - they stream back in around the camera\u0022;\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Remove every object a ClutterComponent has scattered. In Infinite mode the tiles stream straight\r\n    /// back around the camera, so to keep it empty disable the component instead. Not undoable -\r\n    /// terrain_regenerate_clutter with the same seed scatters the same objects again.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003EId of the game object with the ClutterComponent.\u003C/param\u003E\r\n    [McpTool( \u0022terrain_clear_clutter\u0022 )]\r\n    public static string ClearClutter( string id )\r\n    {\r\n        var clutter = FindClutter( id );\r\n\r\n        clutter.Clear();\r\n        SessionOf( clutter.GameObject ).HasUnsavedChanges = true;\r\n\r\n        return $\u0022Cleared the clutter of \u0027{clutter.GameObject.Name}\u0027\u0022;\r\n    }\r\n\r\n    static ClutterComponent FindClutter( string id )\r\n    {\r\n        var go = FindByGuid( id );\r\n        return go.Components.Get\u003CClutterComponent\u003E( FindMode.EverythingInSelf )\r\n            ?? throw new Exception( $\u0022\u0027{go.Name}\u0027 has no ClutterComponent - find_game_objects can search by component type\u0022 );\r\n    }\r\n\r\n    static float Gauss( float x, float sigma ) =\u003E MathF.Exp( -x * x / (2 * sigma * sigma) );\r\n\r\n    static float SmoothStep( float x ) =\u003E x * x * (3 - 2 * x);\r\n\r\n    static float Bilinear( float[] h, int res, float x, float y )\r\n    {\r\n        int ix = (int)x, iy = (int)y;\r\n        float fx = x - ix, fy = y - iy;\r\n        var i = iy * res \u002B ix;\r\n        return h[i] * (1 - fx) * (1 - fy) \u002B h[i \u002B 1] * fx * (1 - fy) \u002B h[i \u002B res] * (1 - fx) * fy \u002B h[i \u002B res \u002B 1] * fx * fy;\r\n    }\r\n\r\n    static List\u003C(int X, int Y, float Weight)\u003E ErosionBrush( int radius )\r\n    {\r\n        var brush = new List\u003C(int, int, float)\u003E();\r\n        for ( var y = -radius; y \u003C= radius; y\u002B\u002B )\r\n        {\r\n            for ( var x = -radius; x \u003C= radius; x\u002B\u002B )\r\n            {\r\n                var d = MathF.Sqrt( x * x \u002B y * y );\r\n                if ( d \u003C= radius ) brush.Add( (x, y, 1f - d / radius) );\r\n            }\r\n        }\r\n\r\n        var total = brush.Sum( b =\u003E b.Item3 );\r\n        return brush.Select( b =\u003E (b.Item1, b.Item2, b.Item3 / total) ).ToList();\r\n    }\r\n\r\n    static int[] Permutation( int seed )\r\n    {\r\n        var p = Enumerable.Range( 0, 256 ).ToArray();\r\n        var rng = new Random( seed );\r\n        for ( var i = 255; i \u003E 0; i-- )\r\n        {\r\n            var j = rng.Next( i \u002B 1 );\r\n            (p[i], p[j]) = (p[j], p[i]);\r\n        }\r\n\r\n        return p.Concat( p ).ToArray();\r\n    }\r\n\r\n    // Classic improved Perlin noise, remapped to 0..1\r\n    static float Perlin( float x, float y, int[] perm )\r\n    {\r\n        int xi = (int)MathF.Floor( x ) \u0026 255, yi = (int)MathF.Floor( y ) \u0026 255;\r\n        float xf = x - MathF.Floor( x ), yf = y - MathF.Floor( y );\r\n        float u = xf * xf * xf * (xf * (xf * 6 - 15) \u002B 10), v = yf * yf * yf * (yf * (yf * 6 - 15) \u002B 10);\r\n        int aa = perm[perm[xi] \u002B yi], ab = perm[perm[xi] \u002B yi \u002B 1], ba = perm[perm[xi \u002B 1] \u002B yi], bb = perm[perm[xi \u002B 1] \u002B yi \u002B 1];\r\n\r\n        static float Grad( int hash, float fx, float fy ) =\u003E (hash \u0026 3) switch\r\n        {\r\n            0 =\u003E fx \u002B fy,\r\n            1 =\u003E -fx \u002B fy,\r\n            2 =\u003E fx - fy,\r\n            _ =\u003E -fx - fy\r\n        };\r\n\r\n        var x1 = Grad( aa, xf, yf ) \u002B u * (Grad( ba, xf - 1, yf ) - Grad( aa, xf, yf ));\r\n        var x2 = Grad( ab, xf, yf - 1 ) \u002B u * (Grad( bb, xf - 1, yf - 1 ) - Grad( ab, xf, yf - 1 ));\r\n        return (x1 \u002B v * (x2 - x1) \u002B 1) / 2;\r\n    }\r\n\r\n    static float Fbm( float x, float y, int octaves, float persistence, float lacunarity, int[] perm )\r\n    {\r\n        float total = 0, amplitude = 1, frequency = 1, max = 0;\r\n        for ( var i = 0; i \u003C octaves; i\u002B\u002B )\r\n        {\r\n            total \u002B= Perlin( x * frequency, y * frequency, perm ) * amplitude;\r\n            max \u002B= amplitude;\r\n            amplitude *= persistence;\r\n            frequency *= lacunarity;\r\n        }\r\n\r\n        return total / max;\r\n    }\r\n}\r\n"},{"Ident":"arenula.leveltools","Path":"Editor/TerrainTools.cs","FileName":"TerrainTools.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":449884,"IsPrivate":false,"Code":"using System;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing Editor;\r\nusing Editor.Mcp;\r\nusing Sandbox;\r\nusing static LevelTools.McpHelpers;\r\nusing static LevelTools.TerrainEdit;\r\n\r\nnamespace LevelTools;\r\n\r\n[McpToolset( \u0022terrain\u0022, \u0022Heightmap terrain - create terrains, read and sculpt heights, generate noise, erosion and stamps, import and export heightmaps, manage and paint terrain materials and holes, and regenerate clutter\u0022 )]\r\npublic static class TerrainTools\r\n{\r\n    public enum HeightMode { Set, Raise, Lower, Flatten, Smooth }\r\n\r\n    public enum Falloff { Linear, Smooth, None }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Create a game object with a flat Terrain whose data is embedded in the scene, as adding a Terrain\r\n    /// in the editor does. Size and maximum height can be changed later with set_component (TerrainSize,\r\n    /// TerrainHeight). The user can undo this. Returns the new object\u0027s id - shape it with\r\n    /// terrain_set_height, terrain_noise or terrain_stamp, and give it materials with terrain_add_material.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022name\u0022\u003EName for the new object.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003EWorld position of the terrain\u0027s corner as \u0027x,y,z\u0027. The terrain extends along \u002BX and \u002BY from it.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022size\u0022\u003EWidth and length in units.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022height\u0022\u003EMaximum height in units. Heights are stored as fractions of it.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022resolution\u0022\u003EHeightmap texels per side: 256, 512, 1024, 2048, 4096 or 8192.\u003C/param\u003E\r\n    [McpTool( \u0022terrain_create\u0022 )]\r\n    public static object Create( string name = \u0022Terrain\u0022, Vector3? position = null, float size = 1024f, float height = 512f, int resolution = 512 )\r\n    {\r\n        if ( resolution \u003C 256 || resolution \u003E 8192 || !System.Numerics.BitOperations.IsPow2( resolution ) )\r\n            throw new Exception( $\u0022Resolution {resolution} isn\u0027t one the terrain editor offers - use 256, 512, 1024, 2048, 4096 or 8192\u0022 );\r\n\r\n        var p = position ?? Vector3.Zero;\r\n        RequireFinite( \u0022position, size and height\u0022, p.x, p.y, p.z, size, height );\r\n        if ( size \u003C= 0 || height \u003C= 0 )\r\n            throw new Exception( \u0022Size and height must both be above zero\u0022 );\r\n\r\n        var session = ActiveSession();\r\n\r\n        using var sceneScope = session.Scene.Push();\r\n        using var undoScope = session.UndoScope( \u0022Create Terrain\u0022 ).WithGameObjectCreations().Push();\r\n\r\n        var go = session.Scene.CreateObject();\r\n        go.Name = name;\r\n        go.WorldPosition = p;\r\n\r\n        var storage = new TerrainStorage { TerrainSize = size, TerrainHeight = height };\r\n        storage.SetResolution( resolution );\r\n\r\n        // Without this a storage made in code saves as a null reference and the terrain is empty on reload - the inspector does the same\r\n        storage.EmbeddedResource = new Sandbox.Resources.EmbeddedResource { ResourceCompiler = \u0022embed\u0022 };\r\n\r\n        var terrain = go.Components.Create\u003CTerrain\u003E( false );\r\n        terrain.Storage = storage;\r\n        terrain.Enabled = true;\r\n\r\n        return new { Id = go.Id, ComponentId = terrain.Id, Name = go.Name, Position = go.WorldPosition, Size = size, Height = height, Resolution = resolution };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// A terrain\u0027s size, maximum height, resolution, clipmap settings, the range of heights it holds, and\r\n    /// its materials with the index each one paints with.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003ETerrain game object id. Empty means the scene\u0027s only terrain.\u003C/param\u003E\r\n    [McpTool.ReadOnly( \u0022terrain_get_info\u0022 )]\r\n    public static object GetInfo( string id = \u0022\u0022 )\r\n    {\r\n        var terrain = ForRead( id );\r\n        var storage = terrain.Storage;\r\n        var heights = storage.HeightMap;\r\n\r\n        return new\r\n        {\r\n            Id = terrain.GameObject.Id,\r\n            ComponentId = terrain.Id,\r\n            Name = terrain.GameObject.Name,\r\n            Enabled = terrain.Active,\r\n            Position = terrain.WorldPosition,\r\n            Size = storage.TerrainSize,\r\n            MaxHeight = storage.TerrainHeight,\r\n            storage.Resolution,\r\n            Storage = storage.EmbeddedResource is not null ? \u0022embedded in the scene\u0022 : storage.ResourcePath,\r\n            terrain.ClipMapLodLevels,\r\n            terrain.SubdivisionFactor,\r\n            LowestHeight = MathF.Round( HeightOf( terrain, heights.Min() ), 2 ),\r\n            HighestHeight = MathF.Round( HeightOf( terrain, heights.Max() ), 2 ),\r\n            Materials = storage.Materials.Select( ( m, i ) =\u003E new { Index = i, Name = m?.ResourceName, Path = m?.ResourcePath } ).ToArray()\r\n        };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// The terrain height at a world position, from the heightmap texel under it. Height is above the\r\n    /// terrain\u0027s own base; SurfaceZ is the world Z of the surface there.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003EWorld position as \u0027x,y,z\u0027. Only x and y matter.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003ETerrain game object id. Empty means the scene\u0027s only terrain.\u003C/param\u003E\r\n    [McpTool.ReadOnly( \u0022terrain_get_height\u0022 )]\r\n    public static object GetHeight( Vector3 position, string id = \u0022\u0022 )\r\n    {\r\n        var terrain = ForRead( id );\r\n        var texel = RequireTexel( terrain, position );\r\n        var height = HeightOf( terrain, terrain.Storage.HeightMap[texel.y * terrain.Storage.Resolution \u002B texel.x] );\r\n\r\n        var local = terrain.WorldTransform.PointToLocal( position );\r\n        var surface = terrain.WorldTransform.PointToWorld( new Vector3( local.x, local.y, height ) );\r\n\r\n        return new { Id = terrain.GameObject.Id, Height = MathF.Round( height, 3 ), SurfaceZ = MathF.Round( surface.z, 3 ), Texel = texel, MaxHeight = terrain.Storage.TerrainHeight };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Sample a square grid of terrain heights centred on a position, with the lowest, highest and average.\r\n    /// Heights[row][column]: rows run from -Y to \u002BY, columns from -X to \u002BX. Samples off the terrain are null.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003ECentre of the square as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022regionSize\u0022\u003ESide length of the square in units.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022samples\u0022\u003ESamples per side, 2 to 64.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003ETerrain game object id. Empty means the scene\u0027s only terrain.\u003C/param\u003E\r\n    [McpTool.ReadOnly( \u0022terrain_get_height_region\u0022 )]\r\n    public static object GetHeightRegion( Vector3 position, float regionSize = 100f, [Sandbox.Range( 2, 64 )] int samples = 10, string id = \u0022\u0022 )\r\n    {\r\n        var terrain = ForRead( id );\r\n        var step = regionSize / (samples - 1);\r\n        var start = position - new Vector3( regionSize / 2, regionSize / 2, 0 );\r\n\r\n        var heights = new float?[samples][];\r\n        for ( var row = 0; row \u003C samples; row\u002B\u002B )\r\n        {\r\n            heights[row] = new float?[samples];\r\n            for ( var column = 0; column \u003C samples; column\u002B\u002B )\r\n            {\r\n                if ( TexelAt( terrain, start \u002B new Vector3( column * step, row * step, 0 ) ) is { } t )\r\n                    heights[row][column] = MathF.Round( HeightOf( terrain, terrain.Storage.HeightMap[t.y * terrain.Storage.Resolution \u002B t.x] ), 2 );\r\n            }\r\n        }\r\n\r\n        var found = heights.SelectMany( x =\u003E x ).Where( x =\u003E x.HasValue ).Select( x =\u003E x.Value ).ToArray();\r\n        if ( found.Length == 0 )\r\n            throw new Exception( $\u0022No sample of that square falls on the terrain \u0027{terrain.GameObject.Name}\u0027 - terrain_get_info shows its position and size\u0022 );\r\n\r\n        return new { Id = terrain.GameObject.Id, Lowest = found.Min(), Highest = found.Max(), Average = MathF.Round( found.Average(), 2 ), Heights = heights };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Sculpt a circle of the heightmap. Set moves heights toward height, Raise and Lower add or subtract\r\n    /// it, Flatten moves them toward the height under the centre and Smooth toward their neighbours\u0027\r\n    /// average. Strength and falloff scale the change toward the rim. The user can undo this. Check the\r\n    /// result with terrain_get_height.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022position\u0022\u003EBrush centre as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022mode\u0022\u003EHow heights change.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022height\u0022\u003ETarget height above the terrain base for Set; the amount for Raise and Lower. Unused by Flatten and Smooth.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022radius\u0022\u003EBrush radius in units.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022strength\u0022\u003E0 to 1, how far each texel moves toward its target at the centre.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022falloff\u0022\u003EHow strength fades to the rim.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003ETerrain game object id. Empty means the scene\u0027s only terrain.\u003C/param\u003E\r\n    [McpTool( \u0022terrain_set_height\u0022 )]\r\n    public static object SetHeight( Vector3 position, HeightMode mode = HeightMode.Set, float height = 0f, float radius = 50f,\r\n        [Sandbox.Range( 0, 1 )] float strength = 1f, Falloff falloff = Falloff.Linear, string id = \u0022\u0022 )\r\n    {\r\n        RequireFinite( \u0022height and strength\u0022, height, strength );\r\n        var (terrain, session) = ForEdit( id );\r\n        var map = terrain.Storage.HeightMap;\r\n        var res = terrain.Storage.Resolution;\r\n        var brush = BrushAt( terrain, position, radius );\r\n\r\n        var centreHeight = 0f;\r\n        if ( mode == HeightMode.Flatten )\r\n        {\r\n            var centre = RequireTexel( terrain, position );\r\n            centreHeight = HeightOf( terrain, map[centre.y * res \u002B centre.x] );\r\n        }\r\n\r\n        // Smooth reads the untouched heights, so the result doesn\u0027t depend on the order texels are visited\r\n        var source = mode == HeightMode.Smooth ? (ushort[])map.Clone() : map;\r\n\r\n        var changed = 0;\r\n        CommitHeights( session, terrain, $\u0022Terrain {mode}\u0022, brush.Region, () =\u003E changed = brush.ForEach( ( i, _, _, t ) =\u003E\r\n        {\r\n            var weight = strength * falloff switch\r\n            {\r\n                Falloff.Smooth =\u003E 1f - t * t * (3f - 2f * t),\r\n                Falloff.None =\u003E 1f,\r\n                _ =\u003E 1f - t\r\n            };\r\n\r\n            var current = HeightOf( terrain, map[i] );\r\n            var target = mode switch\r\n            {\r\n                HeightMode.Raise =\u003E current \u002B height * weight,\r\n                HeightMode.Lower =\u003E current - height * weight,\r\n                HeightMode.Flatten =\u003E current \u002B (centreHeight - current) * weight,\r\n                HeightMode.Smooth =\u003E current \u002B (HeightOf( terrain, Average( source, res, i, 6 ) ) - current) * weight,\r\n                _ =\u003E current \u002B (height - current) * weight\r\n            };\r\n\r\n            map[i] = RawOf( terrain, target );\r\n        } ) );\r\n\r\n        return new { Id = terrain.GameObject.Id, Mode = mode.ToString(), TexelsChanged = changed };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Replace the whole heightmap from a file in the project. A .r16 or .raw file is read as 16-bit\r\n    /// little-endian heights, as the editor\u0027s own Import Heightmap reads it. A .r8 file is read as 8-bit\r\n    /// heights scaled to the full height range - the editor\u0027s importer keeps the raw byte instead, so the\r\n    /// same .r8 gives a terrain 257 times taller here. Raw files must be square and match the terrain\u0027s\r\n    /// resolution. Any other file is read as an image, resized to the resolution, with brightness as\r\n    /// height. The user can undo this.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022path\u0022\u003EFile path relative to the project folder, e.g. \u0027heightmaps/island.png\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003ETerrain game object id. Empty means the scene\u0027s only terrain.\u003C/param\u003E\r\n    [McpTool( \u0022terrain_import_heightmap\u0022 )]\r\n    public static object ImportHeightmap( string path, string id = \u0022\u0022 )\r\n    {\r\n        var (terrain, session) = ForEdit( id );\r\n        var file = ProjectPath( path );\r\n\r\n        if ( !File.Exists( file ) )\r\n            throw new Exception( $\u0022No file at \u0027{path}\u0027 in the project\u0022 );\r\n\r\n        var res = terrain.Storage.Resolution;\r\n        var heights = Path.GetExtension( file ).ToLowerInvariant() switch\r\n        {\r\n            \u0022.r16\u0022 or \u0022.raw\u0022 =\u003E ReadRaw( file, res, 2 ),\r\n            \u0022.r8\u0022 =\u003E ReadRaw( file, res, 1 ),\r\n            _ =\u003E ReadImage( file, res )\r\n        };\r\n\r\n        CommitHeights( session, terrain, \u0022Import Heightmap\u0022, Whole( terrain ), () =\u003E heights.CopyTo( terrain.Storage.HeightMap, 0 ) );\r\n\r\n        return new { Id = terrain.GameObject.Id, Imported = path, Resolution = res, LowestHeight = HeightOf( terrain, heights.Min() ), HighestHeight = HeightOf( terrain, heights.Max() ) };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Write the heightmap to a file in the project, replacing any file already there - this cannot be\r\n    /// undone. A .r16 or .raw path writes exact 16-bit little-endian heights that terrain_import_heightmap\r\n    /// and the editor\u0027s Import Heightmap read back; a .png path writes an 8-bit grayscale image, which\r\n    /// loses precision. Other extensions are refused. Changes no scene state.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022path\u0022\u003EFile path relative to the project folder ending in .r16, .raw or .png, e.g. \u0027heightmaps/island.r16\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022id\u0022\u003ETerrain game object id. Empty means the scene\u0027s only terrain.\u003C/param\u003E\r\n    [McpTool( \u0022terrain_export_heightmap\u0022 )]\r\n    public static object ExportHeightmap( string path, string id = \u0022\u0022 )\r\n    {\r\n        var terrain = ForRead( id );\r\n        var file = ProjectPath( path );\r\n        var heights = terrain.Storage.HeightMap;\r\n        var res = terrain.Storage.Resolution;\r\n        var extension = Path.GetExtension( file ).ToLowerInvariant();\r\n\r\n        // The write replaces the file outright, so only paths that are heightmaps by name may be overwritten\r\n        if ( extension is not (\u0022.r16\u0022 or \u0022.raw\u0022 or \u0022.png\u0022) )\r\n            throw new Exception( $\u0022\u0027{path}\u0027 isn\u0027t a heightmap path - end it in .r16 or .raw for exact 16-bit heights, or .png for an 8-bit image\u0022 );\r\n\r\n        byte[] bytes;\r\n\r\n        if ( extension is \u0022.r16\u0022 or \u0022.raw\u0022 )\r\n        {\r\n            bytes = new byte[heights.Length * 2];\r\n            Buffer.BlockCopy( heights, 0, bytes, 0, bytes.Length );\r\n        }\r\n        else\r\n        {\r\n            using var bitmap = new Bitmap( res, res );\r\n            bitmap.SetPixels( heights.Select( h =\u003E new Color( h / (float)ushort.MaxValue, h / (float)ushort.MaxValue, h / (float)ushort.MaxValue ) ).ToArray() );\r\n            bytes = bitmap.ToPng();\r\n        }\r\n\r\n        var replaced = File.Exists( file );\r\n        Directory.CreateDirectory( Path.GetDirectoryName( file ) );\r\n        File.WriteAllBytes( file, bytes );\r\n\r\n        return new { Id = terrain.GameObject.Id, Written = file, Replaced = replaced, Bytes = bytes.Length, Resolution = res, Format = extension is \u0022.r16\u0022 or \u0022.raw\u0022 ? \u0022r16\u0022 : \u0022png8\u0022 };\r\n    }\r\n\r\n    static ushort Average( ushort[] map, int res, int index, int kernel )\r\n    {\r\n        int cx = index % res, cy = index / res, sum = 0, count = 0;\r\n\r\n        for ( var y = Math.Max( 0, cy - kernel ); y \u003C= Math.Min( res - 1, cy \u002B kernel ); y\u002B\u002B )\r\n        {\r\n            for ( var x = Math.Max( 0, cx - kernel ); x \u003C= Math.Min( res - 1, cx \u002B kernel ); x\u002B\u002B )\r\n            {\r\n                sum \u002B= map[y * res \u002B x];\r\n                count\u002B\u002B;\r\n            }\r\n        }\r\n\r\n        return (ushort)((sum \u002B count / 2) / count);\r\n    }\r\n\r\n    static ushort[] ReadRaw( string file, int res, int bytesPerTexel )\r\n    {\r\n        var bytes = File.ReadAllBytes( file );\r\n\r\n        if ( bytes.Length != res * res * bytesPerTexel )\r\n            throw new Exception( $\u0022That file holds {bytes.Length} bytes, but a {res}x{res} terrain needs {res * res * bytesPerTexel} at {bytesPerTexel * 8} bits - export or resample it at the terrain\u0027s resolution\u0022 );\r\n\r\n        var heights = new ushort[res * res];\r\n\r\n        if ( bytesPerTexel == 2 )\r\n            Buffer.BlockCopy( bytes, 0, heights, 0, bytes.Length );\r\n        else\r\n            for ( var i = 0; i \u003C heights.Length; i\u002B\u002B ) heights[i] = (ushort)(bytes[i] * 257);\r\n\r\n        return heights;\r\n    }\r\n\r\n    static ushort[] ReadImage( string file, int res )\r\n    {\r\n        using var loaded = Bitmap.CreateFromBytes( File.ReadAllBytes( file ) );\r\n\r\n        if ( loaded is null || !loaded.IsValid )\r\n            throw new Exception( $\u0022\u0027{Path.GetFileName( file )}\u0027 isn\u0027t an image the engine can read - use PNG, TGA or JPG, or a .r16 raw heightmap\u0022 );\r\n\r\n        using var sized = loaded.Width == res \u0026\u0026 loaded.Height == res ? null : loaded.Resize( res, res );\r\n\r\n        return (sized ?? loaded).GetPixels()\r\n            .Select( p =\u003E (ushort)(Math.Clamp( p.r * 0.299f \u002B p.g * 0.587f \u002B p.b * 0.114f, 0f, 1f ) * ushort.MaxValue) )\r\n            .ToArray();\r\n    }\r\n}\r\n"},{"Ident":"arenula.leveltools","Path":"Editor/TraceTools.cs","FileName":"TraceTools.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":449884,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing Editor.Mcp;\r\nusing Sandbox;\r\nusing static LevelTools.McpHelpers;\r\n\r\nnamespace LevelTools;\r\n\r\n/// \u003Csummary\u003EWhether a trace hits trigger colliders.\u003C/summary\u003E\r\npublic enum TriggerMode\r\n{\r\n    /// \u003Csummary\u003EPass through triggers - the default.\u003C/summary\u003E\r\n    Ignore,\r\n    /// \u003Csummary\u003EHit triggers as well as solids.\u003C/summary\u003E\r\n    Include,\r\n    /// \u003Csummary\u003EHit triggers and nothing else.\u003C/summary\u003E\r\n    Only,\r\n}\r\n\r\n/// \u003Csummary\u003EOne ray for trace_multi_ray.\u003C/summary\u003E\r\npublic class RaySpec\r\n{\r\n    /// \u003Csummary\u003ERay start as \u0027x,y,z\u0027.\u003C/summary\u003E\r\n    public Vector3 From { get; set; }\r\n\r\n    /// \u003Csummary\u003ERay end as \u0027x,y,z\u0027.\u003C/summary\u003E\r\n    public Vector3 To { get; set; }\r\n}\r\n\r\n[McpToolset( \u0022trace\u0022, \u0022Physics traces with filters - rays, sphere and box casts, ray batches and height grids for placement\u0022 )]\r\npublic static class TraceTools\r\n{\r\n    const int MaxRays = 256;\r\n    const int MaxGridPoints = 1024;\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Trace a ray through the open scene\u0027s physics and report the first thing it hits, with tag,\r\n    /// object and trigger filters. Works in the editor without play mode. On a miss only Hit and\r\n    /// Position (the ray\u0027s end) are returned.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022from\u0022\u003ERay start as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022to\u0022\u003ERay end as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022withAnyTags\u0022\u003EOnly hit objects carrying at least one of these tags.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022withoutTags\u0022\u003ENever hit objects carrying any of these tags.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022ignoreId\u0022\u003EGame object id whose whole hierarchy the trace passes through, e.g. the object being placed.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022triggers\u0022\u003EIgnore (default), Include or Only trigger colliders.\u003C/param\u003E\r\n    [McpTool.ReadOnly( \u0022trace_ray\u0022 )]\r\n    public static object Ray( Vector3 from, Vector3 to, string[] withAnyTags = null, string[] withoutTags = null,\r\n        string ignoreId = \u0022\u0022, TriggerMode triggers = TriggerMode.Ignore )\r\n    {\r\n        RequireVector( \u0022from\u0022, from );\r\n        RequireVector( \u0022to\u0022, to );\r\n\r\n        var t = Filtered( ReadScene().Trace.Ray( from, to ), withAnyTags, withoutTags, ignoreId, triggers );\r\n        return Result( t.Run(), from );\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Sweep a sphere from one point to another and report the first thing it touches - checks whether\r\n    /// something of that size fits along a path. Position is the sphere\u0027s centre where it stopped.\r\n    /// Filters as trace_ray.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022from\u0022\u003ESweep start (sphere centre) as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022to\u0022\u003ESweep end as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022radius\u0022\u003ESphere radius in units, above 0.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022withAnyTags\u0022\u003EOnly hit objects carrying at least one of these tags.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022withoutTags\u0022\u003ENever hit objects carrying any of these tags.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022ignoreId\u0022\u003EGame object id whose whole hierarchy the trace passes through.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022triggers\u0022\u003EIgnore (default), Include or Only trigger colliders.\u003C/param\u003E\r\n    [McpTool.ReadOnly( \u0022trace_sphere_cast\u0022 )]\r\n    public static object SphereCast( Vector3 from, Vector3 to, float radius, string[] withAnyTags = null, string[] withoutTags = null,\r\n        string ignoreId = \u0022\u0022, TriggerMode triggers = TriggerMode.Ignore )\r\n    {\r\n        RequireVector( \u0022from\u0022, from );\r\n        RequireVector( \u0022to\u0022, to );\r\n        RequireFinite( \u0022radius\u0022, radius );\r\n        if ( radius \u003C= 0 ) throw new Exception( \u0022radius must be above 0 - use trace_ray for a zero-width trace\u0022 );\r\n\r\n        var t = Filtered( ReadScene().Trace.Sphere( radius, from, to ), withAnyTags, withoutTags, ignoreId, triggers );\r\n        return Result( t.Run(), from );\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Sweep a box from one point to another and report the first thing it touches - checks whether a\r\n    /// footprint fits before placing something. Position is the box\u0027s centre where it stopped. Filters\r\n    /// as trace_ray.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022from\u0022\u003ESweep start (box centre) as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022to\u0022\u003ESweep end as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022size\u0022\u003EFull box size, corner to corner, as \u0027x,y,z\u0027; each above 0.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022rotation\u0022\u003EBox rotation as \u0027pitch,yaw,roll\u0027. Default axis-aligned.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022withAnyTags\u0022\u003EOnly hit objects carrying at least one of these tags.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022withoutTags\u0022\u003ENever hit objects carrying any of these tags.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022ignoreId\u0022\u003EGame object id whose whole hierarchy the trace passes through.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022triggers\u0022\u003EIgnore (default), Include or Only trigger colliders.\u003C/param\u003E\r\n    [McpTool.ReadOnly( \u0022trace_box_cast\u0022 )]\r\n    public static object BoxCast( Vector3 from, Vector3 to, Vector3 size, Angles? rotation = null, string[] withAnyTags = null,\r\n        string[] withoutTags = null, string ignoreId = \u0022\u0022, TriggerMode triggers = TriggerMode.Ignore )\r\n    {\r\n        RequireVector( \u0022from\u0022, from );\r\n        RequireVector( \u0022to\u0022, to );\r\n        RequirePositive( \u0022size\u0022, size );\r\n\r\n        var t = ReadScene().Trace.Ray( from, to ).Size( size );\r\n        if ( rotation is { } r )\r\n        {\r\n            RequireFinite( \u0022rotation\u0022, r.pitch, r.yaw, r.roll );\r\n            t = t.Rotated( r.ToRotation() );\r\n        }\r\n\r\n        return Result( Filtered( t, withAnyTags, withoutTags, ignoreId, triggers ).Run(), from );\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Trace up to 256 rays with the same filters in one call; Results keep the input order. Each result\r\n    /// is shaped as trace_ray\u0027s.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022rays\u0022\u003EThe rays, each an object with From and To as \u0027x,y,z\u0027.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022withAnyTags\u0022\u003EOnly hit objects carrying at least one of these tags.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022withoutTags\u0022\u003ENever hit objects carrying any of these tags.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022ignoreId\u0022\u003EGame object id whose whole hierarchy every ray passes through.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022triggers\u0022\u003EIgnore (default), Include or Only trigger colliders.\u003C/param\u003E\r\n    [McpTool.ReadOnly( \u0022trace_multi_ray\u0022 )]\r\n    public static object MultiRay( RaySpec[] rays, string[] withAnyTags = null, string[] withoutTags = null,\r\n        string ignoreId = \u0022\u0022, TriggerMode triggers = TriggerMode.Ignore )\r\n    {\r\n        if ( rays is null || rays.Length == 0 || rays.Length \u003E MaxRays )\r\n            throw new Exception( $\u0022Give between 1 and {MaxRays} rays - split a larger batch into several calls\u0022 );\r\n\r\n        var scene = ReadScene();\r\n        var results = new List\u003Cobject\u003E( rays.Length );\r\n\r\n        for ( var i = 0; i \u003C rays.Length; i\u002B\u002B )\r\n        {\r\n            if ( rays[i] is null ) throw new Exception( $\u0022Ray {i} is empty - each ray needs From and To\u0022 );\r\n            RequireVector( $\u0022rays[{i}].From\u0022, rays[i].From );\r\n            RequireVector( $\u0022rays[{i}].To\u0022, rays[i].To );\r\n\r\n            var t = Filtered( scene.Trace.Ray( rays[i].From, rays[i].To ), withAnyTags, withoutTags, ignoreId, triggers );\r\n            results.Add( Result( t.Run(), rays[i].From ) );\r\n        }\r\n\r\n        return new { Count = results.Count, Results = results };\r\n    }\r\n\r\n    /// \u003Csummary\u003E\r\n    /// Sample ground height on an evenly spaced grid by tracing straight down - for finding flat spots\r\n    /// to place things or reading the shape of the ground. Grid points run edge to edge across size.\r\n    /// Heights and Slopes are row-major (rows along y, columns along x); null marks a miss. Slope is the\r\n    /// angle in degrees between the surface normal and straight up. Filters as trace_ray.\r\n    /// \u003C/summary\u003E\r\n    /// \u003Cparam name=\u0022center\u0022\u003EGrid centre as \u0027x,y,z\u0027; rays run from z \u002B height down to z - height.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022size\u0022\u003EGrid extent as \u0027x,y\u0027 in units; each above 0.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022columns\u0022\u003EPoints along x, 2 to 64.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022rows\u0022\u003EPoints along y, 2 to 64. columns times rows is at most 1024.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022height\u0022\u003EHow far above and below center.z each ray reaches, above 0.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022withAnyTags\u0022\u003EOnly hit objects carrying at least one of these tags.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022withoutTags\u0022\u003ENever hit objects carrying any of these tags.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022ignoreId\u0022\u003EGame object id whose whole hierarchy the rays pass through.\u003C/param\u003E\r\n    /// \u003Cparam name=\u0022triggers\u0022\u003EIgnore (default), Include or Only trigger colliders.\u003C/param\u003E\r\n    [McpTool.ReadOnly( \u0022trace_sample_grid\u0022 )]\r\n    public static object SampleGrid( Vector3 center, Vector2 size, int columns = 16, int rows = 16, float height = 10000f,\r\n        string[] withAnyTags = null, string[] withoutTags = null, string ignoreId = \u0022\u0022, TriggerMode triggers = TriggerMode.Ignore )\r\n    {\r\n        RequireVector( \u0022center\u0022, center );\r\n        RequireFinite( \u0022size\u0022, size.x, size.y );\r\n        RequireFinite( \u0022height\u0022, height );\r\n        if ( size.x \u003C= 0 || size.y \u003C= 0 ) throw new Exception( \u0022Both size components must be above 0\u0022 );\r\n        if ( height \u003C= 0 ) throw new Exception( \u0022height must be above 0\u0022 );\r\n        if ( columns \u003C 2 || columns \u003E 64 || rows \u003C 2 || rows \u003E 64 )\r\n            throw new Exception( \u0022columns and rows must each be 2 to 64\u0022 );\r\n        if ( columns * rows \u003E MaxGridPoints )\r\n            throw new Exception( $\u0022columns times rows is {columns * rows}, over the {MaxGridPoints} limit - lower one, or sample in tiles\u0022 );\r\n\r\n        var scene = ReadScene();\r\n        var heights = new float?[columns * rows];\r\n        var slopes = new float?[columns * rows];\r\n        var corner = new Vector3( center.x - size.x / 2, center.y - size.y / 2, center.z );\r\n\r\n        for ( var row = 0; row \u003C rows; row\u002B\u002B )\r\n        {\r\n            for ( var col = 0; col \u003C columns; col\u002B\u002B )\r\n            {\r\n                var x = corner.x \u002B size.x * col / (columns - 1);\r\n                var y = corner.y \u002B size.y * row / (rows - 1);\r\n                var from = new Vector3( x, y, center.z \u002B height );\r\n                var to = new Vector3( x, y, center.z - height );\r\n\r\n                var r = Filtered( scene.Trace.Ray( from, to ), withAnyTags, withoutTags, ignoreId, triggers ).Run();\r\n                if ( !r.Hit ) continue;\r\n\r\n                heights[row * columns \u002B col] = r.EndPosition.z;\r\n                slopes[row * columns \u002B col] = Vector3.GetAngle( r.Normal, Vector3.Up );\r\n            }\r\n        }\r\n\r\n        var hits = heights.Where( h =\u003E h.HasValue ).Select( h =\u003E h.Value ).ToList();\r\n\r\n        return new\r\n        {\r\n            Columns = columns,\r\n            Rows = rows,\r\n            Misses = heights.Length - hits.Count,\r\n            MinZ = hits.Count \u003E 0 ? hits.Min() : (float?)null,\r\n            MaxZ = hits.Count \u003E 0 ? hits.Max() : (float?)null,\r\n            Heights = heights,\r\n            Slopes = slopes,\r\n        };\r\n    }\r\n\r\n    static SceneTrace Filtered( SceneTrace t, string[] withAnyTags, string[] withoutTags, string ignoreId, TriggerMode triggers )\r\n    {\r\n        if ( withAnyTags is { Length: \u003E 0 } ) t = t.WithAnyTags( withAnyTags );\r\n        if ( withoutTags is { Length: \u003E 0 } ) t = t.WithoutTags( withoutTags );\r\n        if ( !string.IsNullOrWhiteSpace( ignoreId ) ) t = t.IgnoreGameObjectHierarchy( FindByGuid( ignoreId ) );\r\n\r\n        return triggers switch\r\n        {\r\n            TriggerMode.Include =\u003E t.HitTriggers(),\r\n            TriggerMode.Only =\u003E t.HitTriggersOnly(),\r\n            _ =\u003E t,\r\n        };\r\n    }\r\n\r\n    static object Result( SceneTraceResult r, Vector3 from )\r\n    {\r\n        if ( !r.Hit ) return new { Hit = false, Position = r.EndPosition };\r\n\r\n        return new\r\n        {\r\n            Hit = true,\r\n            Position = r.EndPosition,\r\n            r.Normal,\r\n            Distance = from.Distance( r.EndPosition ),\r\n            GameObjectId = r.GameObject?.Id,\r\n            Name = r.GameObject?.Name,\r\n            Tags = r.GameObject?.Tags.TryGetAll( true ).ToArray(),\r\n            Surface = r.Surface?.ResourceName,\r\n            r.StartedSolid,\r\n        };\r\n    }\r\n\r\n    static void RequireVector( string name, Vector3 v ) =\u003E RequireFinite( name, v.x, v.y, v.z );\r\n}\r\n"}]}