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

5.82% Statements 12/206
0% Branches 0/48
8.33% Functions 1/12
6.06% Lines 12/198

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 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635                                          1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         8x   8x   8x   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 { PlanarFreehandROIAnnotation } from '../../../types/ToolSpecificAnnotationTypes';
import { polyline } from '../../../utilities/math';
import {
  shouldSmooth,
  getInterpolatedPoints,
} from '../../../utilities/planarFreehandROITool/smoothPoints';
import triggerAnnotationRenderForViewportIds from '../../../utilities/triggerAnnotationRenderForViewportIds';
import { updateContourPolyline } from '../../../utilities/contours';
import findOpenUShapedContourVectorToPeak from './findOpenUShapedContourVectorToPeak';
import { triggerAnnotationModified } from '../../../stateManagement/annotation/helpers/state';
 
const { addCanvasPointsToArray, getSubPixelSpacingAndXYDirections } = polyline;
 
/**
 * Activates the open contour edit event loop.
 */
function activateOpenContourEdit(
  evt: EventTypes.InteractionEventType,
  annotation: PlanarFreehandROIAnnotation,
  viewportIdsToRender: string[]
): void {
  this.isEditingOpen = true;
 
  const eventDetail = evt.detail;
  const { currentPoints, element } = eventDetail;
  const canvasPos = currentPoints.canvas;
  const enabledElement = getEnabledElement(element);
  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.mouseUpOpenContourEditCallback
  );
  element.addEventListener(
    Events.MOUSE_DRAG,
    this.mouseDragOpenContourEditCallback
  );
  element.addEventListener(
    Events.MOUSE_CLICK,
    this.mouseUpOpenContourEditCallback
  );
 
  element.addEventListener(
    Events.TOUCH_END,
    this.mouseUpOpenContourEditCallback
  );
  element.addEventListener(
    Events.TOUCH_DRAG,
    this.mouseDragOpenContourEditCallback
  );
  element.addEventListener(
    Events.TOUCH_TAP,
    this.mouseUpOpenContourEditCallback
  );
  hideElementCursor(element);
}
 
/**
 * Deactivates and cleans up the closed contour edit event loop.
 */
function deactivateOpenContourEdit(element: HTMLDivElement) {
  state.isInteractingWithTool = false;
 
  element.removeEventListener(
    Events.MOUSE_UP,
    this.mouseUpOpenContourEditCallback
  );
  element.removeEventListener(
    Events.MOUSE_DRAG,
    this.mouseDragOpenContourEditCallback
  );
  element.removeEventListener(
    Events.MOUSE_CLICK,
    this.mouseUpOpenContourEditCallback
  );
 
  element.removeEventListener(
    Events.TOUCH_END,
    this.mouseUpOpenContourEditCallback
  );
  element.removeEventListener(
    Events.TOUCH_DRAG,
    this.mouseDragOpenContourEditCallback
  );
  element.removeEventListener(
    Events.TOUCH_TAP,
    this.mouseUpOpenContourEditCallback
  );
  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 dragging
 * the edit line past the end of the open contour.
 */
function mouseDragOpenContourEditCallback(
  evt: EventTypes.InteractionEventType
): boolean {
  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));
 
  // Get pixel spacing in the direction.
  // 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) {
    this.checkForFirstCrossing(evt, false);
  }
 
  this.editData.snapIndex = this.findSnapIndex();
 
  this.editData.fusedCanvasPoints = this.fuseEditPointsWithOpenContour(evt);
 
  if (
    startCrossingIndex !== undefined &&
    this.checkForSecondCrossing(evt, false)
  ) {
    this.removePointsAfterSecondCrossing(false);
    this.finishEditOpenOnSecondCrossing(evt);
  } else if (this.checkIfShouldOverwriteAnEnd(evt)) {
    this.openContourEditOverwriteEnd(evt);
  }
 
  triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
}
 
/**
 * Overwrite the end of the contour with the edit, and then switch to the
 * open contour end edit loop.
 */
function openContourEditOverwriteEnd(
  evt: EventTypes.InteractionEventType
): void {
  const eventDetail = evt.detail;
  const { element } = eventDetail;
  const enabledElement = getEnabledElement(element);
  const { viewport } = enabledElement;
  const { annotation, viewportIdsToRender } = this.commonData;
  const fusedCanvasPoints = this.fuseEditPointsForOpenContourEndEdit();
 
  updateContourPolyline(
    annotation,
    {
      points: fusedCanvasPoints,
      closed: false,
    },
    viewport
  );
 
  const worldPoints = annotation.data.contour.polyline;
 
  // Note: Contours generate from fusedCanvasPoints will be in the direction
  // with the last point being the current mouse position
  annotation.data.handles.points = [
    worldPoints[0],
    worldPoints[worldPoints.length - 1],
  ];
  annotation.data.handles.activeHandleIndex = 1;
 
  triggerAnnotationModified(annotation, element);
 
  this.isEditingOpen = false;
  this.editData = undefined;
  this.commonData = undefined;
 
  // Jump to a normal line edit now.
  this.deactivateOpenContourEdit(element);
  this.activateOpenContourEndEdit(evt, annotation, viewportIdsToRender, null);
}
 
/**
 * Checks if we are moving the `editCanvasPoints` past the end of one of the
 * open contour's `prevCanvasPoint`s.
 */
function checkIfShouldOverwriteAnEnd(
  evt: EventTypes.InteractionEventType
): boolean {
  const eventDetail = evt.detail;
  const { currentPoints, lastPoints } = eventDetail;
  const canvasPos = currentPoints.canvas;
  const lastCanvasPos = lastPoints.canvas;
 
  const { snapIndex, prevCanvasPoints, startCrossingIndex } = this.editData;
 
  if (startCrossingIndex === undefined || snapIndex === undefined) {
    // Edit not started
    return false;
  }
 
  // No snap index can be found, so contour is being edited away from line.
  if (snapIndex === -1) {
    return true;
  }
 
  if (snapIndex !== 0 && snapIndex !== prevCanvasPoints.length - 1) {
    // Not snapping to final index
    return false;
  }
 
  // Work out the angle between the last mouse move and
  // And the current point to the snapped point.
  const p1 = canvasPos;
  const p2 = lastCanvasPos;
  const p3 = prevCanvasPoints[snapIndex];
 
  const a = vec2.create();
  const b = vec2.create();
 
  vec2.set(a, p1[0] - p2[0], p1[1] - p2[1]);
  vec2.set(b, p1[0] - p3[0], p1[1] - p3[1]);
 
  const aDotb = vec2.dot(a, b);
  const magA = Math.sqrt(a[0] * a[0] + a[1] * a[1]);
  const magB = Math.sqrt(b[0] * b[0] + b[1] * b[1]);
 
  const theta = Math.acos(aDotb / (magA * magB));
 
  if (theta < Math.PI / 2) {
    return true;
  }
 
  return false;
}
 
/**
 * This method combines the contour before editing (prevCanvasPoints) with
 * the current edit (editCanvasPoints), to produce a single contour ready for
 * end editing.
 *
 * @privateRemarks In this method we use the following trick to find the
 * optimal contour:
 * - 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 fuseEditPointsForOpenContourEndEdit(): Types.Point2[] {
  const { snapIndex, prevCanvasPoints, editCanvasPoints, startCrossingIndex } =
    this.editData;
 
  const newCanvasPoints = [];
 
  // Note: Generated contours will both be in the direction with the
  // last point being the current mouse position
 
  if (snapIndex === 0) {
    // end -> crossingpoint -> edit
    // Add points from the end of the previous contour, to the crossing point.
    for (let i = prevCanvasPoints.length - 1; i >= startCrossingIndex; i--) {
      const canvasPoint = prevCanvasPoints[i];
 
      newCanvasPoints.push([canvasPoint[0], canvasPoint[1]]);
    }
  } else {
    // start -> crossingpoint -> edit
    // Add points from the orignal contour origin up to the low index.
    for (let i = 0; i < startCrossingIndex; i++) {
      const canvasPoint = prevCanvasPoints[i];
 
      newCanvasPoints.push([canvasPoint[0], canvasPoint[1]]);
    }
  }
 
  const distanceBetweenCrossingIndexAndFirstPoint = vec2.distance(
    prevCanvasPoints[startCrossingIndex],
    editCanvasPoints[0]
  );
 
  const distanceBetweenCrossingIndexAndLastPoint = vec2.distance(
    prevCanvasPoints[startCrossingIndex],
    editCanvasPoints[editCanvasPoints.length - 1]
  );
 
  if (
    distanceBetweenCrossingIndexAndFirstPoint <
    distanceBetweenCrossingIndexAndLastPoint
  ) {
    // In order
    for (let i = 0; i < editCanvasPoints.length; i++) {
      const canvasPoint = editCanvasPoints[i];
 
      newCanvasPoints.push([canvasPoint[0], canvasPoint[1]]);
    }
  } else {
    // reverse
    for (let i = editCanvasPoints.length - 1; i >= 0; i--) {
      const canvasPoint = editCanvasPoints[i];
 
      newCanvasPoints.push([canvasPoint[0], canvasPoint[1]]);
    }
  }
 
  return newCanvasPoints;
}
 
/**
 * 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 use the following trick to find the
 * optimal contour:
 * - 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 fuseEditPointsWithOpenContour(
  evt: EventTypes.InteractionEventType
): Types.Point2[] {
  const { prevCanvasPoints, editCanvasPoints, startCrossingIndex, snapIndex } =
    this.editData;
 
  if (startCrossingIndex === undefined || snapIndex === undefined) {
    return undefined;
  }
 
  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]
  );
 
  const pointsToRender = [];
 
  // Add points from the orignal contour origin up to the low index.
  for (let i = 0; i < lowIndex; i++) {
    const canvasPoint = prevCanvasPoints[i];
 
    pointsToRender.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.
 
  const inPlaceDistance =
    distanceBetweenLowAndFirstPoint + distanceBetweenHighAndLastPoint;
 
  const reverseDistance =
    distanceBetweenLowAndLastPoint + distanceBetweenHighAndFirstPoint;
 
  if (inPlaceDistance < reverseDistance) {
    for (let i = 0; i < augmentedEditCanvasPoints.length; i++) {
      const canvasPoint = augmentedEditCanvasPoints[i];
 
      pointsToRender.push([canvasPoint[0], canvasPoint[1]]);
    }
  } else {
    for (let i = augmentedEditCanvasPoints.length - 1; i >= 0; i--) {
      const canvasPoint = augmentedEditCanvasPoints[i];
 
      pointsToRender.push([canvasPoint[0], canvasPoint[1]]);
    }
  }
 
  // Add points from the original contour's high index up to to its end point.
  for (let i = highIndex; i < prevCanvasPoints.length; i++) {
    const canvasPoint = prevCanvasPoints[i];
 
    pointsToRender.push([canvasPoint[0], canvasPoint[1]]);
  }
 
  return pointsToRender;
}
 
/**
 * On a second crossing, apply edit, and start a new edit from the crossing.
 */
function finishEditOpenOnSecondCrossing(
  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: false,
    },
    viewport
  );
 
  const worldPoints = annotation.data.contour.polyline;
 
  annotation.data.handles.points = [
    worldPoints[0],
    worldPoints[worldPoints.length - 1],
  ];
 
  triggerAnnotationModified(annotation, element);
 
  const lastEditCanvasPoint = editCanvasPoints.pop();
 
  this.editData = {
    prevCanvasPoints: fusedCanvasPoints,
    editCanvasPoints: [lastEditCanvasPoint],
    startCrossingIndex: undefined,
    editIndex: 0,
  };
 
  triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
}
 
/**
 * Completes the edit of the open contour when the mouse button is released.
 */
function mouseUpOpenContourEditCallback(
  evt: EventTypes.InteractionEventType
): void {
  const eventDetail = evt.detail;
  const { element } = eventDetail;
 
  this.completeOpenContourEdit(element);
}
 
/**
 * Completes the edit of the open contour.
 */
function completeOpenContourEdit(element: HTMLDivElement) {
  const enabledElement = getEnabledElement(element);
  const { viewport, renderingEngine } = enabledElement;
 
  const { annotation, viewportIdsToRender } = this.commonData;
  const { fusedCanvasPoints, prevCanvasPoints } = this.editData;
 
  if (fusedCanvasPoints) {
    const updatedPoints = shouldSmooth(this.configuration)
      ? getInterpolatedPoints(
          this.configuration,
          fusedCanvasPoints,
          prevCanvasPoints
        )
      : fusedCanvasPoints;
 
    updateContourPolyline(
      annotation,
      {
        points: updatedPoints,
        closed: false,
      },
      viewport
    );
 
    const worldPoints = annotation.data.contour.polyline;
 
    annotation.data.handles.points = [
      worldPoints[0],
      worldPoints[worldPoints.length - 1],
    ];
 
    // If the annotation is an open U-shaped annotation, find the annotation vector.
    if (annotation.data.isOpenUShapeContour) {
      annotation.data.openUShapeContourVectorToPeak =
        findOpenUShapedContourVectorToPeak(fusedCanvasPoints, viewport);
    }
 
    triggerAnnotationModified(annotation, element);
  }
 
  this.isEditingOpen = false;
  this.editData = undefined;
  this.commonData = undefined;
 
  triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
 
  this.deactivateOpenContourEdit(element);
}
 
/**
 * Completes the edit on a cancel method call during the open
 * contour edit loop.
 */
function cancelOpenContourEdit(element: HTMLDivElement) {
  this.completeOpenContourEdit(element);
}
 
/**
 * Registers the open contour edit loop to the tool instance.
 */
function registerOpenContourEditLoop(toolInstance) {
  toolInstance.activateOpenContourEdit =
    activateOpenContourEdit.bind(toolInstance);
  toolInstance.deactivateOpenContourEdit =
    deactivateOpenContourEdit.bind(toolInstance);
  toolInstance.mouseDragOpenContourEditCallback =
    mouseDragOpenContourEditCallback.bind(toolInstance);
  toolInstance.mouseUpOpenContourEditCallback =
    mouseUpOpenContourEditCallback.bind(toolInstance);
  toolInstance.fuseEditPointsWithOpenContour =
    fuseEditPointsWithOpenContour.bind(toolInstance);
  toolInstance.finishEditOpenOnSecondCrossing =
    finishEditOpenOnSecondCrossing.bind(toolInstance);
  toolInstance.checkIfShouldOverwriteAnEnd =
    checkIfShouldOverwriteAnEnd.bind(toolInstance);
  toolInstance.fuseEditPointsForOpenContourEndEdit =
    fuseEditPointsForOpenContourEndEdit.bind(toolInstance);
  toolInstance.openContourEditOverwriteEnd =
    openContourEditOverwriteEnd.bind(toolInstance);
  toolInstance.cancelOpenContourEdit = cancelOpenContourEdit.bind(toolInstance);
  toolInstance.completeOpenContourEdit =
    completeOpenContourEdit.bind(toolInstance);
}
 
export default registerOpenContourEditLoop;