AABB.fromPoints constructor

AABB.fromPoints(
  1. Iterable<Vec2D> points, {
  2. Mat2D? transform,
  3. double expand = 0,
})

Compute an AABB from a set of points with an optional transform to apply before computing.

Implementation

factory AABB.fromPoints(
  Iterable<Vec2D> points, {
  Mat2D? transform,
  double expand = 0,
}) {
  double minX = double.maxFinite;
  double minY = double.maxFinite;
  double maxX = -double.maxFinite;
  double maxY = -double.maxFinite;

  for (final point in points) {
    var p = transform == null ? point : transform * point;

    final x = p.x;
    final y = p.y;
    if (x < minX) {
      minX = x;
    }
    if (y < minY) {
      minY = y;
    }

    if (x > maxX) {
      maxX = x;
    }
    if (y > maxY) {
      maxY = y;
    }
  }

  // Make sure the box is at least this wide/high
  if (expand != 0) {
    double width = maxX - minX;
    double diff = expand - width;
    if (diff > 0) {
      diff /= 2;
      minX -= diff;
      maxX += diff;
    }
    double height = maxY - minY;
    diff = expand - height;

    if (diff > 0) {
      diff /= 2;
      minY -= diff;
      maxY += diff;
    }
  }
  return AABB.fromValues(minX, minY, maxX, maxY);
}