All files / src/apps/tile-editor geometry-helpers.ts

85% Statements 34/40
83.33% Branches 10/12
100% Functions 3/3
85% Lines 34/40

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 451x     1x 1x 1x   1x 2x 2x 6x 6x 6x 6x 6x 6x 4x 6x 6x 2x 2x   1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x             1x 1x  
import { distanceToSegment } from "../../core/utils/geometry";
import { Point } from "./types";
 
export function translatePoints(points: Point[], offset: Point): Point[] {
  return points.map((p) => ({ x: p.x + offset.x, y: p.y + offset.y }));
}
 
export function pointInPolygon(point: Point, polygon: Point[]): boolean {
  let inside = false;
  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
    const xi = polygon[i].x;
    const yi = polygon[i].y;
    const xj = polygon[j].x;
    const yj = polygon[j].y;
    const intersect =
      (yi > point.y) !== (yj > point.y) &&
      point.x < ((xj - xi) * (point.y - yi)) / (yj - yi + Number.EPSILON) + xi;
    if (intersect) inside = !inside;
  }
  return inside;
}
 
export function pointNearPolyline(
  point: Point,
  polyline: Point[],
  threshold: number,
  closePath: boolean
): boolean {
  for (let i = 0; i < polyline.length - 1; i++) {
    const a = polyline[i];
    const b = polyline[i + 1];
    if (distanceToSegment(point, a, b) <= threshold) {
      return true;
    }
  }
  if (closePath && polyline.length > 1) {
    const a = polyline[polyline.length - 1];
    const b = polyline[0];
    if (distanceToSegment(point, a, b) <= threshold) {
      return true;
    }
  }
  return false;
}