All files / packages/tools/src/tools/annotation/planarFreehandROITool closedContourEditLoop.ts

30.81% Statements 49/159
5% Branches 2/40
55.55% Functions 5/9
32.23% Lines 49/152

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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513                                            1x                   2x   2x 2x 2x 2x 2x       2x   2x       2x         2x             2x                 2x   2x       2x       2x         2x       2x       2x         2x             1x   1x       1x       1x         1x       1x       1x         1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 1x 1x   1x             1x 1x   1x 1x   1x                                                     1x 1x 1x   1x   1x                             8x   8x   8x   8x   8x   8x   8x   8x          
import { vec3, vec2 } from 'gl-matrix';
import { getEnabledElement } from '@cornerstonejs/core';
import type { Types } from '@cornerstonejs/core';
import { state } from '../../../store';
import { Events } from '../../../enums';
import {
  resetElementCursor,
  hideElementCursor,
} from '../../../cursors/elementCursor';
import type { EventTypes } from '../../../types';
import { polyline } from '../../../utilities/math';
import { ContourWindingDirection } from '../../../types/ContourAnnotation';
import type { PlanarFreehandROIAnnotation } from '../../../types/ToolSpecificAnnotationTypes';
import {
  getInterpolatedPoints,
  shouldSmooth,
} from '../../../utilities/planarFreehandROITool/smoothPoints';
import triggerAnnotationRenderForViewportIds from '../../../utilities/triggerAnnotationRenderForViewportIds';
import updateContourPolyline from '../../../utilities/contours/updateContourPolyline';
import { triggerAnnotationModified } from '../../../stateManagement/annotation/helpers/state';
 
const { getSubPixelSpacingAndXYDirections, addCanvasPointsToArray, getArea } =
  polyline;
 
/**
 * Activates the closed contour edit event loop.
 */
function activateClosedContourEdit(
  evt: EventTypes.InteractionEventType,
  annotation: PlanarFreehandROIAnnotation,
  viewportIdsToRender: string[]
): void {
  this.isEditingClosed = true;
 
  const eventDetail = evt.detail;
  const { currentPoints, element } = eventDetail;
  const canvasPos = currentPoints.canvas;
  const enabledElement = getEnabledElement(element);
  Iif (!enabledElement) {
    // Occurs on shutdown
    return;
  }
  const { viewport } = enabledElement;
 
  const prevCanvasPoints = annotation.data.contour.polyline.map(
    viewport.worldToCanvas
  );
 
  const { spacing, xDir, yDir } = getSubPixelSpacingAndXYDirections(
    viewport,
    this.configuration.subPixelResolution
  );
 
  this.editData = {
    prevCanvasPoints,
    editCanvasPoints: [canvasPos],
    startCrossingIndex: undefined,
    editIndex: 0,
  };
 
  this.commonData = {
    annotation,
    viewportIdsToRender,
    spacing,
    xDir,
    yDir,
    movingTextBox: false,
  };
 
  state.isInteractingWithTool = true;
 
  element.addEventListener(
    Events.MOUSE_UP,
    this.mouseUpClosedContourEditCallback
  );
  element.addEventListener(
    Events.MOUSE_DRAG,
    this.mouseDragClosedContourEditCallback
  );
  element.addEventListener(
    Events.MOUSE_CLICK,
    this.mouseUpClosedContourEditCallback
  );
 
  element.addEventListener(
    Events.TOUCH_END,
    this.mouseUpClosedContourEditCallback
  );
  element.addEventListener(
    Events.TOUCH_DRAG,
    this.mouseDragClosedContourEditCallback
  );
  element.addEventListener(
    Events.TOUCH_TAP,
    this.mouseUpClosedContourEditCallback
  );
 
  hideElementCursor(element);
}
 
/**
 * Dectivates and cleans up the closed contour edit event loop.
 */
function deactivateClosedContourEdit(element: HTMLDivElement): void {
  state.isInteractingWithTool = false;
 
  element.removeEventListener(
    Events.MOUSE_UP,
    this.mouseUpClosedContourEditCallback
  );
  element.removeEventListener(
    Events.MOUSE_DRAG,
    this.mouseDragClosedContourEditCallback
  );
  element.removeEventListener(
    Events.MOUSE_CLICK,
    this.mouseUpClosedContourEditCallback
  );
 
  element.removeEventListener(
    Events.TOUCH_END,
    this.mouseUpClosedContourEditCallback
  );
  element.removeEventListener(
    Events.TOUCH_DRAG,
    this.mouseDragClosedContourEditCallback
  );
  element.removeEventListener(
    Events.TOUCH_TAP,
    this.mouseUpClosedContourEditCallback
  );
 
  resetElementCursor(element);
}
 
/**
 * Adds points to the edit line and calculates the preview of the edit to render.
 * Checks if an edit needs to be completed by crossing of lines, or by editing in
 * a way that requires a new edit to keep the contour a simple polygon.
 */
function mouseDragClosedContourEditCallback(
  evt: EventTypes.InteractionEventType
): Types.Point2[] {
  const eventDetail = evt.detail;
  const { currentPoints, element } = eventDetail;
  const worldPos = currentPoints.world;
  const canvasPos = currentPoints.canvas;
  const enabledElement = getEnabledElement(element);
  const { renderingEngine, viewport } = enabledElement;
 
  const { viewportIdsToRender, xDir, yDir, spacing } = this.commonData;
  const { editIndex, editCanvasPoints, startCrossingIndex } = this.editData;
 
  const lastCanvasPoint = editCanvasPoints[editCanvasPoints.length - 1];
  const lastWorldPoint = viewport.canvasToWorld(lastCanvasPoint);
 
  const worldPosDiff = vec3.create();
 
  vec3.subtract(worldPosDiff, worldPos, lastWorldPoint);
 
  const xDist = Math.abs(vec3.dot(worldPosDiff, xDir));
  const yDist = Math.abs(vec3.dot(worldPosDiff, yDir));
 
  // Check that we have moved at least one voxel in each direction.
  if (xDist <= spacing[0] && yDist <= spacing[1]) {
    // Haven't changed world point enough, don't render
    return;
  }
 
  if (startCrossingIndex !== undefined) {
    // Edge case: If the edit line itself crosses, remove part of that edit line so we don't
    // Get isolated regions.
    this.checkAndRemoveCrossesOnEditLine(evt);
  }
 
  const numPointsAdded = addCanvasPointsToArray(
    element,
    editCanvasPoints,
    canvasPos,
    this.commonData
  );
 
  const currentEditIndex = editIndex + numPointsAdded;
 
  this.editData.editIndex = currentEditIndex;
 
  if (startCrossingIndex === undefined && editCanvasPoints.length > 1) {
    // If we haven't found the index of the first crossing yet,
    // see if we can find it.
    this.checkForFirstCrossing(evt, true);
  }
 
  this.editData.snapIndex = this.findSnapIndex();
 
  if (this.editData.snapIndex === -1) {
    // No point on the prevCanvasPoints for the editCanvasPoints line to
    // snap to. Apply edit, and start a new edit as we've gone back on ourselves.
    this.finishEditAndStartNewEdit(evt);
    return;
  }
 
  this.editData.fusedCanvasPoints = this.fuseEditPointsWithClosedContour(evt);
 
  if (
    startCrossingIndex !== undefined &&
    this.checkForSecondCrossing(evt, true)
  ) {
    // Crossed a second time, apply edit, and start a new edit from the crossing.
    this.removePointsAfterSecondCrossing(true);
    this.finishEditAndStartNewEdit(evt);
  }
 
  triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
}
 
/**
 * Finish the current edit, and start a new one.
 */
function finishEditAndStartNewEdit(evt: EventTypes.InteractionEventType): void {
  const eventDetail = evt.detail;
  const { element } = eventDetail;
  const enabledElement = getEnabledElement(element);
  const { viewport, renderingEngine } = enabledElement;
 
  const { annotation, viewportIdsToRender } = this.commonData;
  const { fusedCanvasPoints, editCanvasPoints } = this.editData;
 
  updateContourPolyline(
    annotation,
    {
      points: fusedCanvasPoints,
      closed: true,
      targetWindingDirection: ContourWindingDirection.Clockwise,
    },
    viewport
  );
 
  // If any manual update, triggered on an annotation, then it will be treated as non-autogenerated.
  if (annotation.autoGenerated) {
    annotation.autoGenerated = false;
  }
 
  triggerAnnotationModified(annotation, element);
 
  const lastEditCanvasPoint = editCanvasPoints.pop();
 
  this.editData = {
    prevCanvasPoints: fusedCanvasPoints,
    editCanvasPoints: [lastEditCanvasPoint],
    startCrossingIndex: undefined,
    editIndex: 0,
    snapIndex: undefined,
  };
 
  triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
}
 
/**
 * This method combines the contour before editing (prevCanvasPoints) with
 * the current edit (editCanvasPoints), to produce a renderable preview of the
 * edit. Upon finishing the contour, the preview generated here is written back
 * into the contour state.
 *
 * @privateRemarks In this method we combine a few tricks to find the optimal
 * contour:
 * - As the contour is closed, our edit might stradle the boundary between the
 * last and 0th point of the contour, e.g. a small edit might go from e.g. index
 * 960 to index 4. We therefore calculate two possible contours, and find the
 * one with the biggest area, which will define the actual edit the user desired.
 * - As the contour and the edit can be drawn with different chiralities, we find if
 * the edit line aligns better with the intended cross points in its current order
 * or reversed. We do this by minimising the distance between its ends and the
 * intended crossing points.
 */
function fuseEditPointsWithClosedContour(
  evt: EventTypes.InteractionEventType
): Types.Point2[] {
  const { prevCanvasPoints, editCanvasPoints, startCrossingIndex, snapIndex } =
    this.editData;
 
  if (startCrossingIndex === undefined || snapIndex === undefined) {
    return;
  }
 
  const eventDetail = evt.detail;
  const { element } = eventDetail;
 
  // Augment the editCanvasPoints array, between the end of edit and the snap index.
  const augmentedEditCanvasPoints = [...editCanvasPoints];
 
  addCanvasPointsToArray(
    element,
    augmentedEditCanvasPoints,
    prevCanvasPoints[snapIndex],
    this.commonData
  );
 
  if (augmentedEditCanvasPoints.length > editCanvasPoints.length) {
    // If any points added, remove the last point, which will be a clone of the snapIndex
    augmentedEditCanvasPoints.pop();
  }
 
  // Calculate the distances between the first and last edit points and the origin of the
  // Contour with the snap point. These will be used to see which way around the edit array should be
  // Placed within the preview.
  let lowIndex;
  let highIndex;
 
  if (startCrossingIndex > snapIndex) {
    lowIndex = snapIndex;
    highIndex = startCrossingIndex;
  } else {
    lowIndex = startCrossingIndex;
    highIndex = snapIndex;
  }
 
  const distanceBetweenLowAndFirstPoint = vec2.distance(
    prevCanvasPoints[lowIndex],
    augmentedEditCanvasPoints[0]
  );
 
  const distanceBetweenLowAndLastPoint = vec2.distance(
    prevCanvasPoints[lowIndex],
    augmentedEditCanvasPoints[augmentedEditCanvasPoints.length - 1]
  );
 
  const distanceBetweenHighAndFirstPoint = vec2.distance(
    prevCanvasPoints[highIndex],
    augmentedEditCanvasPoints[0]
  );
 
  const distanceBetweenHighAndLastPoint = vec2.distance(
    prevCanvasPoints[highIndex],
    augmentedEditCanvasPoints[augmentedEditCanvasPoints.length - 1]
  );
 
  // Generate two possible contours that could be intepreted from the edit:
  //
  // pointSet1 => 0 -> low -> edit -> high - max.
  // pointSet2 => low -> high -> edit
  //
  // Depending on the placement of the edit and the origin, either of these could be the intended edit.
  // We'll choose the one with the largest area, as edits are considered to be changes to the original area with
  // A relative change of much less than unity.
 
  // Point Set 1
  const pointSet1 = [];
 
  // Add points from the orignal contour origin up to the low index.
  for (let i = 0; i < lowIndex; i++) {
    const canvasPoint = prevCanvasPoints[i];
 
    pointSet1.push([canvasPoint[0], canvasPoint[1]]);
  }
 
  // Check which orientation of the edit line minimizes the distance between the
  // origial contour low/high points and the start/end nodes of the edit line.
 
  let inPlaceDistance =
    distanceBetweenLowAndFirstPoint + distanceBetweenHighAndLastPoint;
 
  let reverseDistance =
    distanceBetweenLowAndLastPoint + distanceBetweenHighAndFirstPoint;
 
  if (inPlaceDistance < reverseDistance) {
    for (let i = 0; i < augmentedEditCanvasPoints.length; i++) {
      const canvasPoint = augmentedEditCanvasPoints[i];
 
      pointSet1.push([canvasPoint[0], canvasPoint[1]]);
    }
  } else {
    for (let i = augmentedEditCanvasPoints.length - 1; i >= 0; i--) {
      const canvasPoint = augmentedEditCanvasPoints[i];
 
      pointSet1.push([canvasPoint[0], canvasPoint[1]]);
    }
  }
 
  // Add points from the orignal contour's high index up to to its end point.
  for (let i = highIndex; i < prevCanvasPoints.length; i++) {
    const canvasPoint = prevCanvasPoints[i];
 
    pointSet1.push([canvasPoint[0], canvasPoint[1]]);
  }
 
  // Point Set 2
  const pointSet2 = [];
 
  for (let i = lowIndex; i < highIndex; i++) {
    const canvasPoint = prevCanvasPoints[i];
 
    pointSet2.push([canvasPoint[0], canvasPoint[1]]);
  }
 
  inPlaceDistance =
    distanceBetweenHighAndFirstPoint + distanceBetweenLowAndLastPoint;
 
  reverseDistance =
    distanceBetweenHighAndLastPoint + distanceBetweenLowAndFirstPoint;
 
  if (inPlaceDistance < reverseDistance) {
    for (let i = 0; i < augmentedEditCanvasPoints.length; i++) {
      const canvasPoint = augmentedEditCanvasPoints[i];
 
      pointSet2.push([canvasPoint[0], canvasPoint[1]]);
    }
  } else {
    for (let i = augmentedEditCanvasPoints.length - 1; i >= 0; i--) {
      const canvasPoint = augmentedEditCanvasPoints[i];
 
      pointSet2.push([canvasPoint[0], canvasPoint[1]]);
    }
  }
 
  const areaPointSet1 = getArea(pointSet1);
  const areaPointSet2 = getArea(pointSet2);
 
  const pointsToRender: Types.Point2[] =
    areaPointSet1 > areaPointSet2 ? pointSet1 : pointSet2;
 
  return pointsToRender;
}
 
/**
 * Completes the edit of the closed contour when the mouse button is released.
 */
function mouseUpClosedContourEditCallback(
  evt: EventTypes.InteractionEventType
): void {
  const eventDetail = evt.detail;
  const { element } = eventDetail;
 
  this.completeClosedContourEdit(element);
}
 
/**
 * Completes the edit of the closed contour when the mouse button is released.
 */
function completeClosedContourEdit(element: HTMLDivElement) {
  const enabledElement = getEnabledElement(element);
  const { viewport, renderingEngine } = enabledElement;
 
  const { annotation, viewportIdsToRender } = this.commonData;
  const { fusedCanvasPoints, prevCanvasPoints } = this.editData;
 
  Iif (fusedCanvasPoints) {
    const updatedPoints = shouldSmooth(this.configuration, annotation)
      ? getInterpolatedPoints(
          this.configuration,
          fusedCanvasPoints,
          prevCanvasPoints
        )
      : fusedCanvasPoints;
 
    updateContourPolyline(
      annotation,
      {
        points: updatedPoints,
        closed: true,
        targetWindingDirection: ContourWindingDirection.Clockwise,
      },
      viewport
    );
 
    // If any manual update, triggered on an annotation, then it will be treated as non-autogenerated.
    if (annotation.autoGenerated) {
      annotation.autoGenerated = false;
    }
 
    triggerAnnotationModified(annotation, element);
  }
 
  this.isEditingClosed = false;
  this.editData = undefined;
  this.commonData = undefined;
 
  triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
 
  this.deactivateClosedContourEdit(element);
}
 
/**
 * Completes the edit on a cancel method call during the closed
 * contour edit loop.
 */
function cancelClosedContourEdit(element: HTMLDivElement) {
  this.completeClosedContourEdit(element);
}
 
/**
 * Registers the closed contour edit loop to the tool instance.
 */
function registerClosedContourEditLoop(toolInstance): void {
  toolInstance.activateClosedContourEdit =
    activateClosedContourEdit.bind(toolInstance);
  toolInstance.deactivateClosedContourEdit =
    deactivateClosedContourEdit.bind(toolInstance);
  toolInstance.mouseDragClosedContourEditCallback =
    mouseDragClosedContourEditCallback.bind(toolInstance);
  toolInstance.mouseUpClosedContourEditCallback =
    mouseUpClosedContourEditCallback.bind(toolInstance);
  toolInstance.finishEditAndStartNewEdit =
    finishEditAndStartNewEdit.bind(toolInstance);
  toolInstance.fuseEditPointsWithClosedContour =
    fuseEditPointsWithClosedContour.bind(toolInstance);
  toolInstance.cancelClosedContourEdit =
    cancelClosedContourEdit.bind(toolInstance);
  toolInstance.completeClosedContourEdit =
    completeClosedContourEdit.bind(toolInstance);
}
 
export default registerClosedContourEditLoop;