import { Vector3, clamp } from 'math.gl';

// Return the closest point on a line segment
export function getClosestPointOnLine(_ref) {
  var p = _ref.p,
      p1 = _ref.p1,
      p2 = _ref.p2,
      _ref$clampToLine = _ref.clampToLine,
      clampToLine = _ref$clampToLine === undefined ? true : _ref$clampToLine;

  var lineVector = new Vector3(p2).subtract(p1);
  var pointVector = new Vector3(p).subtract(p1);
  var dotProduct = lineVector.dot(pointVector);
  if (clampToLine) {
    dotProduct = clamp(dotProduct, 0, 1);
  }
  return lineVector.lerp(dotProduct);
}

// Return the closest point on a line segment
export function getClosestPointOnPolyline(_ref2) {
  var p = _ref2.p,
      points = _ref2.points;

  p = new Vector3(p);
  var pClosest = null;
  var distanceSquared = Infinity;
  var index = -1;
  for (var i = 0; i < points.length - 1; ++i) {
    var p1 = points[i];
    var p2 = points[i + 1];
    var pClosestOnLine = getClosestPointOnLine({ p: p, p1: p1, p2: p2 });
    var distanceToLineSquared = p.distanceSquared(pClosestOnLine);
    if (distanceToLineSquared < distanceSquared) {
      distanceSquared = distanceToLineSquared;
      pClosest = pClosestOnLine;
      index = i;
    }
  }
  return {
    point: pClosest,
    index: index,
    p1: points[index],
    p2: points[index + 1],
    distanceSquared: distanceSquared,
    distance: Math.sqrt(distanceSquared)
  };
}
//# sourceMappingURL=polyline.js.map