ai/utils/SpatialQuery.cs
// SpatialQuery.cs
using System;
using Sandbox;

public static class SpatialQuery
{
    /// <summary>
    /// Trouve le composant le plus proche dans la scène sans allocation mémoire LINQ.
    /// </summary>
    public static T GetNearest<T>( Vector3 origin, float maxDistance = float.MaxValue, Func<T, bool> filter = null ) where T : Component
    {
        T nearest = null;
        var maxDistSq = maxDistance * maxDistance;
        var bestDistSq = maxDistSq;

        foreach ( var comp in Game.ActiveScene.GetAllComponents<T>() )
        {
            if ( !comp.IsValid ) continue;
            if ( filter != null && !filter( comp ) ) continue;

            var distSq = (comp.WorldPosition - origin).LengthSquared;
            if ( distSq < bestDistSq )
            {
                bestDistSq = distSq;
                nearest = comp;
            }
        }

        return nearest;
    }
}