All files / tools/src/utilities/math/polyline intersectPolyline.ts

0% Statements 0/10
0% Branches 0/4
0% Functions 0/1
0% Lines 0/8

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                                                                     
import type { Types } from '@cornerstonejs/core';
import getFirstLineSegmentIntersectionIndexes from './getFirstLineSegmentIntersectionIndexes';
 
/**
 * Check if two polylines intersect comparing line segment by line segment.
 * @param sourcePolyline - Source polyline
 * @param targetPolyline - Target polyline
 * @returns True if the polylines intersect or false otherwise
 */
export default function intersectPolyline(
  sourcePolyline: Types.Point2[],
  targetPolyline: Types.Point2[]
): boolean {
  // Naive way to detect intersection between polylines in O(n^2).
  // TODO: Implement Bentley Ottmann sweep line algorithm or maybe some
  // algorithm that uses r-tree may make it run faster
  for (let i = 0, sourceLen = sourcePolyline.length; i < sourceLen; i++) {
    const sourceP1 = sourcePolyline[i];
    const sourceP2Index = i === sourceLen - 1 ? 0 : i + 1;
    const sourceP2 = sourcePolyline[sourceP2Index];
 
    const intersectionPointIndexes = getFirstLineSegmentIntersectionIndexes(
      targetPolyline,
      sourceP1,
      sourceP2
    );
 
    if (intersectionPointIndexes?.length === 2) {
      return true;
    }
  }
 
  return false;
}