All files / tools/src/eventListeners/segmentation imageChangeEventListener.ts

90.12% Statements 73/81
76.92% Branches 20/26
92.3% Functions 12/13
90.12% Lines 73/81

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                                    428x 702x       702x   702x       702x   702x 214x     488x             488x           428x                     428x                         1886x 1886x 1886x         1886x   1886x 1375x     511x   511x     511x     511x 74x 74x     511x   74x   74x   511x 473x             38x     38x 38x         38x     38x 2x       38x 38x 38x 38x         38x       38x 38x 38x   38x                 38x 76x     38x     2x     2x           2x                         2x 2x 2x   2x             2x   2x 2x 2x 2x 2x 2x   2x         2x         2x 2x         36x       36x         36x               38x     38x 2x     38x         38x   36x                        
import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray';
import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData';
import type { Types } from '@cornerstonejs/core';
import {
  BaseVolumeViewport,
  getEnabledElement,
  Enums,
  getEnabledElementByIds,
  cache,
  utilities,
} from '@cornerstonejs/core';
import { triggerSegmentationRender } from '../../stateManagement/segmentation/SegmentationRenderingEngine';
import { updateLabelmapSegmentationImageReferences } from '../../stateManagement/segmentation/updateLabelmapSegmentationImageReferences';
import { getCurrentLabelmapImageIdsForViewport } from '../../stateManagement/segmentation/getCurrentLabelmapImageIdForViewport';
import { SegmentationRepresentations } from '../../enums';
import { getLabelmapActorEntries } from '../../stateManagement/segmentation/helpers/getSegmentationActor';
import { getSegmentationRepresentations } from '../../stateManagement/segmentation/getSegmentationRepresentation';
 
const enable = function (element: HTMLDivElement): void {
  Iif (!element) {
    return;
  }
 
  const enabledElement = getEnabledElement(element);
 
  Iif (!enabledElement) {
    return;
  }
 
  const { viewport } = enabledElement;
 
  if (viewport instanceof BaseVolumeViewport) {
    return;
  }
 
  element.addEventListener(
    Enums.Events.PRE_STACK_NEW_IMAGE,
    _imageChangeEventListener as EventListener
  );
  // this listener handles the segmentation modifications
  // we only listen to the image_rendered once and then remove it
  // the main event to listen here is the stack_new_image
  element.addEventListener(
    Enums.Events.IMAGE_RENDERED,
    _imageChangeEventListener as EventListener
  );
};
 
const disable = function (element: HTMLDivElement): void {
  element.removeEventListener(
    Enums.Events.PRE_STACK_NEW_IMAGE,
    _imageChangeEventListener as EventListener
  );
  element.removeEventListener(
    Enums.Events.IMAGE_RENDERED,
    _imageChangeEventListener as EventListener
  );
};
 
const perViewportManualTriggers = new Map();
 
/**
 *  When the image is rendered, check what tools can be rendered for this element.
 *
 * - First we get all tools which are active, passive or enabled on the element.
 * - If any of these tools have a `renderAnnotation` method, then we render them.
 * - Note that these tools don't necessarily have to be instances of  `AnnotationTool`,
 *   Any tool may register a `renderAnnotation` method (e.g. a tool that displays an overlay).
 *
 * @param evt - The normalized IMAGE_RENDERED event.
 */
function _imageChangeEventListener(evt) {
  const eventData = evt.detail;
  const { viewportId, renderingEngineId } = eventData;
  const { viewport } = getEnabledElementByIds(
    viewportId,
    renderingEngineId
  ) as { viewport: Types.IStackViewport };
 
  const representations = getSegmentationRepresentations(viewportId);
 
  if (!representations?.length) {
    return;
  }
 
  const labelmapRepresentations = representations.filter(
    (representation) =>
      representation.type === SegmentationRepresentations.Labelmap
  );
 
  const actors = viewport.getActors();
 
  // Update the maps
  labelmapRepresentations.forEach((representation) => {
    const { segmentationId } = representation;
    updateLabelmapSegmentationImageReferences(viewportId, segmentationId);
  });
 
  const labelmapActors = labelmapRepresentations
    .flatMap((representation) => {
      return getLabelmapActorEntries(viewportId, representation.segmentationId);
    })
    .filter((actor) => actor !== undefined);
 
  if (!labelmapActors.length) {
    return;
  }
 
  // we need to check for the current viewport state with the current representations
  // is there any extra actor that needs to be removed
  // or any actor that needs to be added (which it is added later down), but remove
  // it here if it is not needed
  labelmapActors.forEach((actor) => {
    // if cannot find a representation for this actor means it has stuck around
    // form previous renderings and should be removed
    const validActor = labelmapRepresentations.find((representation) => {
      const derivedImageIds = getCurrentLabelmapImageIdsForViewport(
        viewportId,
        representation.segmentationId
      );
 
      return derivedImageIds?.includes(actor.referencedId);
    });
 
    if (!validActor) {
      viewport.removeActors([actor.uid]);
    }
  });
 
  labelmapRepresentations.forEach((representation) => {
    const { segmentationId } = representation;
    const currentImageId = viewport.getCurrentImageId();
    const derivedImageIds = getCurrentLabelmapImageIdsForViewport(
      viewportId,
      segmentationId
    );
 
    Iif (!derivedImageIds) {
      return;
    }
 
    let shouldTriggerSegmentationRender = false;
    const updateSegmentationActor = (derivedImageId) => {
      const derivedImage = cache.getImage(derivedImageId);
 
      Iif (!derivedImage) {
        console.warn(
          'No derived image found in the cache for segmentation representation',
          representation
        );
        return;
      }
 
      // re-use the old labelmap actor for the new image labelmap for speed and memory
      const segmentationActorInput = actors.find(
        (actor) => actor.referencedId === derivedImageId
      );
 
      if (!segmentationActorInput) {
        // i guess we need to create here
        const { dimensions, spacing, direction } =
          viewport.getImageDataMetadata(derivedImage);
 
        const currentImage =
          cache.getImage(currentImageId) ||
          ({
            imageId: currentImageId,
          } as Types.IImage);
 
        const { origin: currentOrigin } =
          viewport.getImageDataMetadata(currentImage);
 
        // IMPORTANT: We need to make sure that the origin of the segmentation
        // is the same as the current image origin. This is because due to some
        // floating point precision issues, when coming from volume to stack
        // the origin of the segmentation can be slightly different from the
        // current image origin. This can cause the segmentation to be rendered
        // in the wrong location.
        // Todo: This will not work for segmentations that are not in the same frame
        // of reference or derived from the same image. This can happen when we have
        // a segmentation that happens to exist in the same space as the image but is
        // not derived from it. We need to find a way to handle this case, but don't think
        // it makes sense to do it for the stack viewport, as the volume viewport is designed to handle this case.
        const originToUse = currentOrigin;
        const constructor = derivedImage.voxelManager.getConstructor();
        const newPixelData = derivedImage.voxelManager.getScalarData();
 
        const scalarArray = vtkDataArray.newInstance({
          name: 'Pixels',
          numberOfComponents: 1,
          // @ts-expect-error
          values: new constructor(newPixelData),
        });
 
        const imageData = vtkImageData.newInstance();
 
        imageData.setDimensions(dimensions[0], dimensions[1], 1);
        imageData.setSpacing(spacing);
        imageData.setDirection(direction);
        imageData.setOrigin(originToUse);
        imageData.getPointData().setScalars(scalarArray);
        imageData.modified();
 
        viewport.addImages([
          {
            imageId: derivedImageId,
            representationUID: `${segmentationId}-${SegmentationRepresentations.Labelmap}-${derivedImage.imageId}`,
            callback: ({ imageActor }) => {
              imageActor.getMapper().setInputData(imageData);
            },
          },
        ]);
 
        shouldTriggerSegmentationRender = true;
        return;
      } else {
        // if actor found
        // update the image data
 
        const segmentationImageData = segmentationActorInput.actor
          .getMapper()
          .getInputData();
 
        Iif (segmentationImageData.setDerivedImage) {
          // Update the derived image data, whether vtk or other as appropriate
          // to the actor(s) displaying the data.
          segmentationImageData.setDerivedImage(derivedImage);
        } else {
          utilities.updateVTKImageDataWithCornerstoneImage(
            segmentationImageData,
            derivedImage
          );
        }
      }
    };
 
    derivedImageIds.forEach(updateSegmentationActor);
    // if one or more actors were added to the viewport
    // we need to trigger a segmentation render
    if (shouldTriggerSegmentationRender) {
      triggerSegmentationRender(viewportId);
    }
 
    viewport.render();
 
    // This is put here to make sure that the segmentation is rendered
    // for the initial image as well after that we don't need it since
    // stack new image is called when changing slices
    if (evt.type === Enums.Events.IMAGE_RENDERED) {
      // unsubscribe after the initial render
      viewport.element.removeEventListener(
        Enums.Events.IMAGE_RENDERED,
        _imageChangeEventListener as EventListener
      );
    }
  });
}
 
export default {
  enable,
  disable,
};