polygon method

List<Point> polygon(
  1. List<Point> points,
  2. BBox bbox
)

Sutherland-Hodgeman polygon clipping algorithm.

Implementation

List<Point> polygon(List<Point> points, BBox bbox) {
  List<Point> result = [];
  if (points.isEmpty) return result;

  // clip against each side of the clip rectangle
  for (int edge = 1; edge <= 8; edge *= 2) {
    result = [];
    Point prev = points.last;
    bool prevInside = (_bitCode(prev, bbox) & edge) == 0;

    for (final p in points) {
      final bool inside = (_bitCode(p, bbox) & edge) == 0;

      // if segment goes through the clip window, add an intersection
      if (inside != prevInside)
        result.add(_intersect(prev, p, edge, bbox));

      if (inside) result.add(p); // add a point if it's inside

      prev = p;
      prevInside = inside;
    }

    points = result;

    if (points.isEmpty) break;
  }

  return result;
}