Editor/CourseWallBuilderTool.Snap.cs

The code implements snapping logic for a wall builder tool in the editor. It identifies and prioritizes target points and connecting lines, such as tiles, posts, and grid points, based on cursor position and current placement constraints.

using Sandbox;
using Editor;
using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// Snapping: one pass per frame from the raw hit to the point a click would use, and the floor
/// tiles the targets and the floor-follow come from. Nothing is remembered between frames but the
/// run.
/// </summary>
public sealed partial class CourseWallBuilderTool
{
	/// <summary>A snap target this close (in units, in the ground plane) takes the point; the nearest one when several are.</summary>
	const float SoftSnapDistance = 30f;

	/// <summary>A target more than this above or below the hit is on another level and does not count; a hit on a rail top (10 to 20 up) still reaches the floor targets under it.</summary>
	const float SnapHeightTolerance = 100f;

	/// <summary>Shift: the pending segment's direction from the last post is locked to a multiple of this angle (22.5 degrees), in radians.</summary>
	const float DirectionStep = MathF.PI / 8f;

	/// <summary>Default mode: a direction within this of a 45 degree step (or of a right angle to the previous rail) snaps to it.</summary>
	const float CoarseAngleTolerance = 5f * MathF.PI / 180f;

	/// <summary>Default mode: a direction within this of a 22.5 degree step snaps to it.</summary>
	const float FineAngleTolerance = 3f * MathF.PI / 180f;

	/// <summary>How close the cursor has to be to the run's first post to close the loop: a quarter tile.</summary>
	const float FirstPostCatch = KitShape.Tile / 4f;

	/// <summary>The spacing of the point grid: tile corners and edge midpoints, 100 apart.</summary>
	const float PointGrid = KitShape.Tile / 2f;

	/// <summary>
	/// What the snap pass picked. Point kinds (a post, the loop close, a tile corner, an edge
	/// midpoint, a tile centre, a 100 point on the locked axis, a grid point) get a marker; line kinds
	/// (a tile edge, a grid line, the first-post alignment) draw the line itself; Direction draws the
	/// axis. A post or the loop close is joined rather than doubled; anything else gets a post.
	/// </summary>
	enum SnapKind
	{
		None,
		LoopClose,
		Post,
		TileCorner,
		TileMid,
		TileCentre,
		AxisPoint,
		GridPoint,
		TileEdge,
		GridLine,
		Align,
		Direction,
	}

	static bool IsPointKind( SnapKind kind ) => kind is SnapKind.LoopClose or SnapKind.Post or SnapKind.TileCorner or SnapKind.TileMid or SnapKind.TileCentre or SnapKind.AxisPoint or SnapKind.GridPoint;
	static bool IsLineKind( SnapKind kind ) => kind is SnapKind.TileEdge or SnapKind.GridLine or SnapKind.Align;

	/// <summary>One frame's snap: the point to use, what it is, and the blue lines to draw for it (the snapped line, the axis, the alignment).</summary>
	readonly record struct SnapResult( Vector3 Point, SnapKind Kind, List<(Vector3 from, Vector3 to)> Lines );

	readonly record struct PointTarget( Vector3 Point, SnapKind Kind );

	/// <summary>A line target: a segment (a tile edge) or a long line through two points (a grid line, an alignment line), and what it is.</summary>
	readonly record struct LineTarget( Vector3 A, Vector3 B, SnapKind Kind, bool Segment );

	/// <summary>The snap distance between the hit and a target: in the ground plane, or out of reach when the heights differ by more than <see cref="SnapHeightTolerance"/>.</summary>
	static float SnapDistance( Vector3 hit, Vector3 target ) => MathF.Abs( hit.z - target.z ) > SnapHeightTolerance ? float.MaxValue : hit.WithZ( 0f ).Distance( target.WithZ( 0f ) );

	/// <summary>True when the cursor is on the run's first post and the run has three posts or more, so a rail back to it makes a loop rather than doubling the first rail.</summary>
	bool FirstPostNear( Vector3 point ) => Continuing && _run.Points.Count >= 3 && _run.First.Distance( point ) <= FirstPostCatch;

	/// <summary>
	/// The snap pass, from the raw hit, every frame.
	///
	/// Default: a soft snap within <see cref="SoftSnapDistance"/>. The nearest point target wins first
	/// (the graph's posts, tile corners, edge midpoints, tile centres, the 100 points along a locked
	/// direction), then the nearest line target (tile edges, grid lines, alignment with the run's
	/// first post along X or Y, the point being the foot of the perpendicular), then the direction
	/// alone (45 and 22.5 degree steps and right angles off the previous rail, within their
	/// tolerances), else free.
	///
	/// Shift: a hard snap with no distance limit. A post, tile corner, midpoint or centre within reach
	/// still wins; otherwise the direction is locked to the nearest 22.5 degrees and the point goes to
	/// the nearest 100 grid point on that axis (where the axis carries any), else to the nearest 100
	/// grid point to the projected cursor; with no run open, to the nearest 100 grid point.
	///
	/// Ctrl: nothing but the loop close. The loop close always comes first. A post given as exclude
	/// (the one being moved) is no target.
	/// </summary>
	SnapResult Resolve( WallGraph graph, GameObject parent, Vector3 raw, bool shift, bool ctrl, WallPost exclude = null )
	{
		var result = ResolveCore( graph, parent, raw, shift, ctrl, exclude, out var candidates );
		if ( DebugLog ) DebugSnap( raw, candidates, result, shift, ctrl );
		return result;
	}

	SnapResult ResolveCore( WallGraph graph, GameObject parent, Vector3 raw, bool shift, bool ctrl, WallPost exclude, out List<PointTarget> candidates )
	{
		candidates = new List<PointTarget>();
		var lines = new List<(Vector3 from, Vector3 to)>();
		if ( FirstPostNear( raw ) ) return new SnapResult( _run.First, SnapKind.LoopClose, lines );
		if ( ctrl ) return new SnapResult( raw, SnapKind.None, lines );

		Vector3? from = Continuing ? _run.Last : null;
		var frame = GridFrame( parent, raw, out var phase );

		// The direction: the hard 22.5 lock with Shift, the soft steps without. The axis gives the 100 points along it and the direction fallback.
		Vector3? axisDirection = null;
		Vector3? onAxis = null;
		if ( from is { } f )
		{
			var flat = (raw - f).WithZ( 0f );
			if ( flat.Length >= 1f )
			{
				var mouseAngle = MathF.Atan2( flat.y, flat.x );
				var angle = shift ? MathF.Round( mouseAngle / DirectionStep ) * DirectionStep : SoftAngle( mouseAngle );
				if ( angle is { } locked )
				{
					axisDirection = new Vector3( MathF.Cos( locked ), MathF.Sin( locked ), 0f );
					onAxis = (f + axisDirection.Value * Vector3.Dot( flat, axisDirection.Value )).WithZ( raw.z );
				}
			}
		}

		// Point targets.
		var points = candidates;
		foreach ( var post in graph.Posts ) if ( post != exclude ) points.Add( new PointTarget( post.Point, SnapKind.Post ) );
		var tiles = TileTargets( parent, raw );
		points.AddRange( tiles.points );
		if ( !shift && from is { } f1 && axisDirection is { } d1 && onAxis is { } a1 )
			foreach ( var g in AxisGridPoints( frame, phase, f1, d1, a1 ) ) if ( g.Distance( f1 ) > PostSize ) points.Add( new PointTarget( g, SnapKind.AxisPoint ) );

		var nearestPoint = points.Count == 0 ? (PointTarget?)null : points.OrderBy( p => SnapDistance( raw, p.Point ) ).First();
		if ( nearestPoint is { } np && SnapDistance( raw, np.Point ) <= SoftSnapDistance && (!shift || np.Kind is SnapKind.Post or SnapKind.TileCorner or SnapKind.TileMid or SnapKind.TileCentre) )
		{
			if ( np.Kind == SnapKind.AxisPoint && from is { } f2 ) lines.Add( (f2, np.Point) );
			return new SnapResult( np.Point, np.Kind, lines );
		}

		if ( shift )
		{
			// The hard grid: on the locked axis when it carries grid points, else the nearest grid point.
			if ( from is { } f3 && axisDirection is { } d3 && onAxis is { } a3 )
			{
				var onAxisGrid = AxisGridPoints( frame, phase, f3, d3, a3 ).Where( g => g.Distance( f3 ) > PostSize ).OrderBy( g => g.Distance( a3 ) ).FirstOrDefault();
				if ( onAxisGrid != default )
				{
					lines.Add( (f3, onAxisGrid) );
					return new SnapResult( onAxisGrid, SnapKind.AxisPoint, lines );
				}
				// No grid point on this axis (a 22.5 or 67.5 degree run): the nearest grid point to the projection, never the post itself.
				var nearGrid = NearestGridPoint( frame, phase, a3 );
				if ( nearGrid.Distance( f3 ) <= PostSize ) nearGrid = NearestGridPoint( frame, phase, a3 + d3 * PointGrid );
				lines.Add( (f3, nearGrid) );
				return new SnapResult( nearGrid, SnapKind.GridPoint, lines );
			}
			return new SnapResult( NearestGridPoint( frame, phase, raw ), SnapKind.GridPoint, lines );
		}

		// Line targets: the nearest within reach, the point being the foot of the perpendicular.
		var lineTargets = new List<LineTarget>( tiles.edges );
		lineTargets.AddRange( GridLines( frame, phase, raw ) );
		if ( Continuing )
		{
			lineTargets.Add( new LineTarget( _run.First, _run.First + Vector3.Forward, SnapKind.Align, false ) );
			lineTargets.Add( new LineTarget( _run.First, _run.First + Vector3.Left, SnapKind.Align, false ) );
		}
		LineTarget? bestLine = null;
		Vector3 bestFoot = default;
		var bestDistance = SoftSnapDistance + 0.001f;   // inclusive: a line exactly at the reach still snaps, like a point does
		foreach ( var line in lineTargets )
		{
			var foot = line.Segment ? ClosestOnSegment( line.A, line.B, raw ) : ClosestOnLine( line.A, line.B, raw );
			if ( foot is not { } fp ) continue;
			var distance = SnapDistance( raw, fp );
			if ( distance < bestDistance ) { bestDistance = distance; bestLine = line; bestFoot = fp; }
		}
		if ( bestLine is { } bl )
		{
			var along = (bl.B - bl.A).WithZ( 0f ).Normal;
			if ( bl.Segment ) lines.Add( (bl.A, bl.B) );
			else if ( bl.Kind == SnapKind.Align ) lines.Add( (bl.A, bestFoot + along * (Vector3.Dot( bestFoot - bl.A, along ) >= 0f ? 1f : -1f) * KitShape.Tile) );
			else lines.Add( (bestFoot - along * KitShape.Tile * 2f, bestFoot + along * KitShape.Tile * 2f) );
			return new SnapResult( bestFoot, bl.Kind, lines );
		}

		// The direction alone.
		if ( from is { } f4 && onAxis is { } a4 )
		{
			lines.Add( (f4, a4) );
			return new SnapResult( a4, SnapKind.Direction, lines );
		}
		return new SnapResult( raw, SnapKind.None, lines );
	}

	/// <summary>golf_wall_debug: while the cursor is within 40 units of an edge midpoint or an axis 100 point, one line with the nearest of each (distance, point, height gap) and what the pass picked.</summary>
	void DebugSnap( Vector3 raw, List<PointTarget> candidates, SnapResult result, bool shift, bool ctrl )
	{
		var mid = candidates.Where( c => c.Kind == SnapKind.TileMid ).OrderBy( c => SnapDistance( raw, c.Point ) ).FirstOrDefault();
		var axis = candidates.Where( c => c.Kind == SnapKind.AxisPoint ).OrderBy( c => SnapDistance( raw, c.Point ) ).FirstOrDefault();
		var midD = mid.Kind == SnapKind.TileMid ? SnapDistance( raw, mid.Point ) : float.MaxValue;
		var axisD = axis.Kind == SnapKind.AxisPoint ? SnapDistance( raw, axis.Point ) : float.MaxValue;
		if ( midD > 40f && axisD > 40f ) return;
		string Near( PointTarget c, float d ) => d == float.MaxValue ? "none" : $"{d:0.#} at {c.Point} (dz {raw.z - c.Point.z:0.#})";
		Log.Info( $"golf_wall_debug: raw {raw} | midpoint {Near( mid, midD )} | axis-100 {Near( axis, axisD )} | picked {result.Kind} -> {result.Point} | candidates {candidates.Count}, run {Continuing}, shift {shift}, ctrl {ctrl}" );
	}

	/// <summary>
	/// Default mode's soft direction snap: the angle (radians, world) snapped to a 45 degree step
	/// when within <see cref="CoarseAngleTolerance"/>, to a 22.5 degree step when within
	/// <see cref="FineAngleTolerance"/>, or to a right angle (or straight on) off the run's previous
	/// rail when within the coarse tolerance; the closest of those that qualify, or null for free.
	/// </summary>
	float? SoftAngle( float angle )
	{
		float? best = null;
		var bestOff = float.MaxValue;
		void Consider( float step, float tolerance, float origin )
		{
			var snapped = origin + MathF.Round( (angle - origin) / step ) * step;
			var off = MathF.Abs( WrapAngle( angle - snapped ) );
			if ( off <= tolerance && off < bestOff ) { bestOff = off; best = snapped; }
		}
		Consider( MathF.PI / 4f, CoarseAngleTolerance, 0f );
		Consider( DirectionStep, FineAngleTolerance, 0f );
		if ( Continuing && _run.Points.Count >= 2 )
		{
			var previous = (_run.Points[^1] - _run.Points[^2]).WithZ( 0f );
			if ( previous.Length >= 1f ) Consider( MathF.PI / 2f, CoarseAngleTolerance, MathF.Atan2( previous.y, previous.x ) );
		}
		return best;
	}

	/// <summary>An angle in radians wrapped into -pi..pi.</summary>
	static float WrapAngle( float angle )
	{
		while ( angle > MathF.PI ) angle -= MathF.Tau;
		while ( angle < -MathF.PI ) angle += MathF.Tau;
		return angle;
	}

	/// <summary>The floor tiles near the point as targets: every corner of a tile's top, the midpoint of each top edge and the tile's centre as point targets, each top edge as a line segment. At the tile's own height.</summary>
	(List<PointTarget> points, List<LineTarget> edges) TileTargets( GameObject parent, Vector3 point )
	{
		var points = new List<PointTarget>();
		var edges = new List<LineTarget>();
		foreach ( var renderer in TileRenderers( parent ) )
		{
			var go = renderer.GameObject;
			if ( go.WorldPosition.WithZ( 0f ).Distance( point.WithZ( 0f ) ) > KitShape.Tile * 1.5f ) continue;
			var corners = GolfHoleEdgeWalls.TopCorners( renderer.Model );
			if ( corners is null ) continue;
			var world = corners.Select( c => go.WorldTransform.PointToWorld( c ) ).ToArray();
			var centre = Vector3.Zero;
			for ( var i = 0; i < world.Length; i++ )
			{
				var a = world[i];
				var b = world[(i + 1) % world.Length];
				centre += a / world.Length;
				points.Add( new PointTarget( a, SnapKind.TileCorner ) );
				points.Add( new PointTarget( (a + b) * 0.5f, SnapKind.TileMid ) );
				edges.Add( new LineTarget( a, b, SnapKind.TileEdge, true ) );
			}
			points.Add( new PointTarget( centre, SnapKind.TileCentre ) );
		}
		return (points, edges);
	}

	/// <summary>The point of the segment a-b nearest to p, measured in the ground plane; null for a degenerate segment.</summary>
	static Vector3? ClosestOnSegment( Vector3 a, Vector3 b, Vector3 p )
	{
		var ab = (b - a).WithZ( 0f );
		var length2 = ab.LengthSquared;
		if ( length2 < 1f ) return null;
		var t = Math.Clamp( Vector3.Dot( (p - a).WithZ( 0f ), ab ) / length2, 0f, 1f );
		return a + (b - a) * t;
	}

	/// <summary>The point of the infinite line through a and b nearest to p in the ground plane, at p's height.</summary>
	static Vector3? ClosestOnLine( Vector3 a, Vector3 b, Vector3 p )
	{
		var ab = (b - a).WithZ( 0f );
		if ( ab.LengthSquared < 0.0001f ) return null;
		var t = Vector3.Dot( (p - a).WithZ( 0f ), ab ) / ab.LengthSquared;
		return (a + ab * t).WithZ( p.z );
	}

	/// <summary>The two grid lines nearest the point in the tile frame (the tile-edge grid, every 200, 100 off the tile centres), as line targets at the point's height.</summary>
	static IEnumerable<LineTarget> GridLines( Transform frame, float phase, Vector3 point )
	{
		var local = frame.PointToLocal( point );
		float Snap( float v ) => MathF.Round( (v - phase) / KitShape.Tile ) * KitShape.Tile + phase;
		var sx = Snap( local.x );
		var sy = Snap( local.y );
		yield return new LineTarget( frame.PointToWorld( new Vector3( sx, local.y - 1f, local.z ) ), frame.PointToWorld( new Vector3( sx, local.y + 1f, local.z ) ), SnapKind.GridLine, false );
		yield return new LineTarget( frame.PointToWorld( new Vector3( local.x - 1f, sy, local.z ) ), frame.PointToWorld( new Vector3( local.x + 1f, sy, local.z ) ), SnapKind.GridLine, false );
	}

	/// <summary>The nearest point of the 100 grid (tile corners and edge midpoints) to a point, in the tile frame, at the point's height.</summary>
	static Vector3 NearestGridPoint( Transform frame, float phase, Vector3 point )
	{
		var local = frame.PointToLocal( point );
		float Snap( float v ) => MathF.Round( (v - phase) / PointGrid ) * PointGrid + phase;
		return frame.PointToWorld( new Vector3( Snap( local.x ), Snap( local.y ), local.z ) );
	}

	/// <summary>The 100 grid points on the axis through a run's last post along a direction, near the projected point: the three nearest along X or Y; on a diagonal the points where both coordinates sit on the grid (there when the run starts on the grid); none on other angles.</summary>
	static IEnumerable<Vector3> AxisGridPoints( Transform frame, float phase, Vector3 from, Vector3 direction, Vector3 onAxis )
	{
		float Snap( float v ) => MathF.Round( (v - phase) / PointGrid ) * PointGrid + phase;
		var p = frame.PointToLocal( onAxis );
		var d = (frame.Rotation.Inverse * direction).WithZ( 0f );
		if ( d.Length < 0.01f ) yield break;
		d = d.Normal;
		if ( MathF.Abs( d.x ) < 0.01f )
		{
			var sy = Snap( p.y );
			foreach ( var y in new[] { sy - PointGrid, sy, sy + PointGrid } ) yield return frame.PointToWorld( new Vector3( p.x, y, p.z ) );
			yield break;
		}
		if ( MathF.Abs( d.y ) < 0.01f )
		{
			var sx = Snap( p.x );
			foreach ( var x in new[] { sx - PointGrid, sx, sx + PointGrid } ) yield return frame.PointToWorld( new Vector3( x, p.y, p.z ) );
			yield break;
		}
		var gx0 = Snap( p.x );
		foreach ( var gx in new[] { gx0 - PointGrid, gx0, gx0 + PointGrid } )
		{
			var t = (gx - p.x) / d.x;
			var y = p.y + d.y * t;
			if ( MathF.Abs( y - Snap( y ) ) < 1f ) yield return frame.PointToWorld( new Vector3( gx, Snap( y ), p.z ) );
		}
	}

	/// <summary>The grid the point snaps to: the nearest floor tile's frame with its corner grid (lines 100 from the tile centre, every 200, so posts land where tiles meet), or the world with the plain 200 grid when no tile is near.</summary>
	Transform GridFrame( GameObject parent, Vector3 point, out float phase )
	{
		var tile = NearestTile( parent, point );
		if ( tile.IsValid() )
		{
			phase = KitShape.Tile / 2f;
			return tile.WorldTransform.WithScale( 1f );
		}
		phase = 0f;
		return Transform.Zero;
	}

	// ---------------------------------------------------------------- floor tiles

	/// <summary>The floor pieces (kit or trench tiles, cup tiles, ramps) under the parent, or in the whole scene when there is no parent.</summary>
	IEnumerable<ModelRenderer> TileRenderers( GameObject parent )
	{
		var renderers = parent.IsValid()
			? parent.Components.GetAll<ModelRenderer>( FindMode.EverythingInSelfAndDescendants )
			: Scene.GetAllComponents<ModelRenderer>();
		foreach ( var renderer in renderers )
		{
			var go = renderer.GameObject;
			if ( !go.IsValid() || !go.Enabled || go.Tags.Has( GolfHoleEdgeWalls.Tag ) ) continue;
			if ( GolfHoleEdgeWalls.TopCorners( renderer.Model ) is null ) continue;
			yield return renderer;
		}
	}

	/// <summary>The floor piece whose footprint is nearest the point, within 1.5 tiles and 100 in height; null when none is.</summary>
	GameObject NearestTile( GameObject parent, Vector3 point )
	{
		GameObject best = null;
		var bestDistance = KitShape.Tile * 1.5f;
		foreach ( var renderer in TileRenderers( parent ) )
		{
			var go = renderer.GameObject;
			var local = go.WorldTransform.PointToLocal( point );
			if ( MathF.Abs( local.z ) > 100f ) continue;
			var distance = MathF.Max( MathF.Abs( local.x ), MathF.Abs( local.y ) ) - KitShape.Tile / 2f;
			if ( distance < bestDistance ) { bestDistance = distance; best = go; }
		}
		return best;
	}

	/// <summary>
	/// Where to look for the floor under a group's posts: the hole the group belongs to, so a wall
	/// group that holds no tiles itself still finds the tiles beside it; null (the whole scene) when
	/// the group sits outside any hole.
	/// </summary>
	GameObject FloorScope( GameObject group )
	{
		for ( var go = ParentFor( group ); go.IsValid(); go = go.Parent )
			if ( go.GetComponent<GolfHoleCollision>() is not null || go.Name.StartsWith( "Hole ", StringComparison.OrdinalIgnoreCase ) ) return go;
		return null;
	}

	/// <summary>
	/// The floor under a point, read from the floor pieces themselves (a trace would land on posts
	/// and rails): among the tiles whose 200 x 200 footprint holds the point, the one whose top is
	/// nearest the reference height; a ramp's top rises across it. Null when no tile is under the
	/// point.
	/// </summary>
	(Vector3 point, bool sloped)? FloorUnder( GameObject scope, Vector3 point, float referenceZ )
	{
		(Vector3 point, bool sloped)? best = null;
		var bestGap = float.MaxValue;
		foreach ( var renderer in TileRenderers( scope ) )
		{
			var go = renderer.GameObject;
			var local = go.WorldTransform.PointToLocal( point );
			if ( MathF.Abs( local.x ) > KitShape.Tile / 2f + 0.5f || MathF.Abs( local.y ) > KitShape.Tile / 2f + 0.5f ) continue;
			var ramp = (renderer.Model?.Name ?? "").Contains( "ramp", StringComparison.OrdinalIgnoreCase );
			var topLocalZ = ramp ? KitShape.RampRise * (local.x + KitShape.Tile / 2f) / KitShape.Tile : 0f;
			var top = go.WorldTransform.PointToWorld( new Vector3( local.x, local.y, topLocalZ ) );
			var gap = MathF.Abs( top.z - referenceZ );
			if ( gap < bestGap ) { bestGap = gap; best = (top, ramp); }
		}
		return best;
	}

	/// <summary>True when the floor tile under a post's foot is a ramp (the post's gizmo then gets its Z arrow); false on a flat tile or no tile.</summary>
	bool FloorIsSloped( GameObject group, Vector3 foot ) => FloorUnder( FloorScope( group ), foot, foot.z ) is { } floor && floor.sloped;
}