All files / tools/src/utilities/math/fan fanUtils.ts

0% Statements 0/74
0% Branches 0/20
0% Functions 0/14
0% Lines 0/68

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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import type { Types } from '@cornerstonejs/core';
 
/**
 * Represents an angular interval, where the first element is the start angle
 * and the second element is the end angle. Angles are in degrees.
 * If the end angle is less than the start angle, it implies the interval
 * crosses the 0/360 degree boundary.
 */
export type Interval = Types.Point2;
 
/**
 * Represents a pair of points that define a sector of a fan.
 * These points, along with a center point, define an angular interval.
 */
export type FanPair = [Types.Point2, Types.Point2];
 
/**
 * Represents a collection of FanPair objects.
 */
export type FanPairs = FanPair[];
 
/**
 * Normalizes an angle to be within the range [0, 360).
 *
 * @param angle - The angle in degrees.
 * @returns The normalized angle.
 */
function normalizeAngle(angle: number): number {
  return ((angle % 360) + 360) % 360;
}
 
/**
 * Calculates the angle of a point relative to a center point.
 * The angle is measured in degrees, counter-clockwise from the positive x-axis.
 *
 * @param center - The center point.
 * @param point - The point for which to calculate the angle.
 * @returns The angle in degrees, normalized to [0, 360).
 */
export function angleFromCenter(
  center: Types.Point2,
  point: Types.Point2
): number {
  const dx = point[0] - center[0];
  const dy = point[1] - center[1];
  const angle = Math.atan2(dy, dx) * (180 / Math.PI);
  return normalizeAngle(angle);
}
 
/**
 * Creates an angle interval from a pair of points and a center.
 * The interval [start, end] represents an angular sector.
 * If the end angle is less than the start angle, the angles are switched
 *
 * @param center - The center point of the fan.
 * @param pair - A pair of points defining the start and end of the fan sector.
 * @returns An array representing the angular interval [startAngle, endAngle] in degrees.
 */
export function intervalFromPoints(
  center: Types.Point2,
  pair: FanPair
): Types.Point2 {
  const start = angleFromCenter(center, pair[0]);
  const end = angleFromCenter(center, pair[1]);
  return start < end ? [start, end] : [end, start];
}
 
/**
 * Merges overlapping angular intervals.
 * The input intervals are sorted by their start angles.
 *
 * @param intervals - An array of angular intervals to merge.
 * @returns A new array of merged, non-overlapping angular intervals.
 */
export function mergeIntervals(intervals: Interval[]): Interval[] {
  if (!intervals.length) {
    return [];
  }
  // Sort intervals by their start angle.
  intervals.sort((a, b) => a[0] - b[0]);
 
  const merged: Interval[] = [intervals[0].slice() as Interval];
 
  for (let i = 1; i < intervals.length; i++) {
    const last = merged[merged.length - 1];
    const current = intervals[i];
 
    // If the current interval overlaps with the last merged interval, merge them.
    if (current[0] <= last[1]) {
      last[1] = Math.max(last[1], current[1]);
    } else {
      // Otherwise, add the current interval as a new merged interval.
      merged.push(current.slice() as Interval);
    }
  }
  return merged;
}
 
/**
 * Subtract a list of intervals from a target interval.
 *
 * All intervals are of the form [start, end] where start ≤ end.
 * They are treated as *closed* on both ends.  (If you need half-open
 * semantics, adjust the comparison operators as noted in comments.)
 *
 * @param {Interval[]} blocked  intervals to remove
 * @param {Interval}        target   interval to subtract from
 * @returns {Interval[]}        gaps that remain
 */
export function subtractIntervals(
  blocked: Interval[],
  target: Interval
): Interval[] {
  const [T0, T1] = target;
  if (T1 <= T0) {
    return [];
  } // empty / invalid target
 
  /* ---- 1. clip “blocked” intervals to the target and keep only overlaps ---- */
  const overlaps = blocked
    .map(([a, b]) => [Math.max(a, T0), Math.min(b, T1)])
    .filter(([a, b]) => b > a); //  use “>=” for closed–open
 
  if (overlaps.length === 0) {
    return [[T0, T1]];
  } // nothing blocked at all
 
  /* ---- 2. merge overlaps so we deal with a single, sorted union ---- */
  overlaps.sort((p, q) => p[0] - q[0]);
  const merged = [];
  let [curA, curB] = overlaps[0];
 
  for (let i = 1; i < overlaps.length; i++) {
    const [a, b] = overlaps[i];
    if (a <= curB) {
      // intervals touch / overlap  →  extend the current one
      curB = Math.max(curB, b);
    } else {
      merged.push([curA, curB]);
      [curA, curB] = [a, b];
    }
  }
  merged.push([curA, curB]); // last segment
 
  /* ---- 3. walk through the merged blocks and collect the gaps ---- */
  const gaps = [];
  let cursor = T0;
 
  for (const [a, b] of merged) {
    if (a > cursor) {
      gaps.push([cursor, a]);
    } // gap before this block
    cursor = Math.max(cursor, b); // advance behind the block
  }
  if (cursor < T1) {
    gaps.push([cursor, T1]);
  } // trailing gap
 
  return gaps;
}
 
/**
 * Clips an inner angular interval against a set of merged outer angular intervals.
 * This function finds the parts of the inner interval that are also covered by any of the outer intervals.
 *
 * @param inner - The inner angular interval [startAngle, endAngle].
 * @param outerMerged - An array of merged, non-overlapping outer angular intervals.
 * @returns An array of clipped angular intervals. Each interval is a part of the `inner`
 * interval that intersects with one of the `outerMerged` intervals.
 */
export function clipInterval(
  inner: Types.Point2,
  outerMerged: Interval[]
): Interval[] {
  const result: Interval[] = [];
  for (const out of outerMerged) {
    // Find the intersection of the inner interval and the current outer interval.
    const start = Math.max(inner[0], out[0]);
    const end = Math.min(inner[1], out[1]);
 
    // If there is a valid intersection (start < end), add it to the result.
    if (start < end) {
      result.push([start, end]);
    }
  }
  return result;
}
 
/**
 * Calculates the percentage of an inner fan (defined by `innerFanPairs`)
 * that is covered by an outer fan (defined by `outerFanPairs`), relative
 * to a common center point.
 *
 * This is useful for determining how much of a region of interest (inner fan)
 * falls within a larger field of view or permissible area (outer fan).
 *
 * The calculation involves:
 * 1. Converting all fan pairs (both outer and inner) to angular intervals.
 * 2. Merging the outer fan intervals to get a set of non-overlapping angular sectors
 *    representing the total outer fan area.
 * 3. For each inner fan interval:
 *    a. Clipping it against the merged outer fan intervals. This finds the portions
 *       of the inner fan sector that are actually covered by the outer fan.
 * 4. Merging all these clipped inner intervals to avoid double-counting areas
 *    where multiple inner fan sectors might overlap within the outer fan.
 * 5. Calculating the total angular span of the merged outer fan and the
 *    total angular span of the final merged (and clipped) inner fan.
 * 6. The percentage is (total inner span / total outer span) * 100.
 *
 * @param center - The common center point for both fans.
 * @param outerFanPairs - An array of point pairs defining the sectors of the outer fan.
 * @param innerFanPairs - An array of point pairs defining the sectors of the inner fan.
 * @returns The percentage of the inner fan covered by the outer fan, clamped between 0 and 100.
 * Returns 0 if the outer fan has no area (outerTotal is 0).
 */
export function calculateInnerFanPercentage(
  center: Types.Point2,
  outerFanPairs: FanPairs,
  innerFanPairs: FanPairs
): number {
  // Convert outer fan pairs to angular intervals
  const outerIntervals = outerFanPairs.map((pair) =>
    intervalFromPoints(center, pair)
  ) as Interval[];
  // Merge outer intervals to get a clean representation of the outer fan area
  const mergedOuter = mergeIntervals(outerIntervals);
  // Calculate the total angular span of the outer fan
  const outerTotal = mergedOuter.reduce((sum, [a, b]) => sum + (b - a), 0);
 
  // If the outer fan has no area, the percentage of coverage is 0.
  if (outerTotal === 0) {
    return 0;
  }
 
  const clippedInnerIntervals: Interval[] = [];
 
  // For each inner fan sector:
  for (const pair of innerFanPairs) {
    // Convert the inner fan pair to an angular interval
    const innerInterval = intervalFromPoints(center, pair) as Interval;
    // Clip this inner interval against the merged outer fan area
    const clipped = clipInterval(innerInterval, mergedOuter);
    // Add all resulting clipped portions to our list
    clippedInnerIntervals.push(...clipped);
  }
 
  // Merge all clipped inner intervals. This is important to correctly sum the
  // total inner area that's covered, especially if inner fan sectors overlap
  // after being clipped by the outer fan.
  const mergedInner = mergeIntervals(clippedInnerIntervals);
  // Calculate the total angular span of the (clipped and merged) inner fan
  const innerTotal = mergedInner.reduce((sum, [a, b]) => sum + (b - a), 0);
 
  // Calculate the percentage
  const percentage = (innerTotal / outerTotal) * 100;
 
  // Clamp the percentage between 0 and 100
  return Math.min(100, Math.max(0, percentage));
}