All files / tools/src/stateManagement/segmentation SegmentationRenderingEngine.ts

96.51% Statements 83/86
85.29% Branches 29/34
100% Functions 21/21
96.51% Lines 83/86

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                                                  428x           428x                   428x 428x 428x 428x                   1526x     1526x                 2635x 2635x     428x 2847x 2847x 2721x         2847x 2847x   2847x 4709x   4709x 4497x         4497x 3409x       212x   212x 212x         2847x               3785x               7012x   3015x 3015x     3997x 4763x     3997x                 3997x 3815x         3815x       428x 3785x   3785x   3785x 4723x       3785x     3785x 3785x     3785x 2851x 2851x 2851x             4723x   4723x 401x   4322x   4322x       4322x     4322x   4886x     852x     4886x   4886x   4886x 4886x         4886x             4322x 4322x 4886x 4886x     4312x   4312x         4312x 4872x           4872x             4322x 4322x           4322x           852x 8x   852x     852x 8x 8x                 1526x                 2635x     428x            
import type { Types } from '@cornerstonejs/core';
import {
  triggerEvent,
  eventTarget,
  Enums,
  getRenderingEngines,
  getEnabledElementByViewportId,
} from '@cornerstonejs/core';
import {
  SegmentationRepresentations,
  Events as csToolsEvents,
} from '../../enums';
 
import type { SegmentationRenderedEventDetail } from '../../types/EventTypes';
import Representations from '../../enums/SegmentationRepresentations';
import { getSegmentationRepresentations } from './getSegmentationRepresentation';
import type { SegmentationRepresentation } from '../../types/SegmentationStateTypes';
import surfaceDisplay from '../../tools/displayTools/Surface/surfaceDisplay';
import contourDisplay from '../../tools/displayTools/Contour/contourDisplay';
import labelmapDisplay from '../../tools/displayTools/Labelmap/labelmapDisplay';
import { addTool } from '../../store/addTool';
import { state } from '../../store/state';
import PlanarFreehandContourSegmentationTool from '../../tools/annotation/PlanarFreehandContourSegmentationTool';
import { getToolGroupForViewport } from '../../store/ToolGroupManager';
 
const renderers = {
  [Representations.Labelmap]: labelmapDisplay,
  [Representations.Contour]: contourDisplay,
  [Representations.Surface]: surfaceDisplay,
};
 
const planarContourToolName = PlanarFreehandContourSegmentationTool.toolName;
 
/**
 * SegmentationRenderingEngine is a class that is responsible for rendering
 * segmentations. It will render the segmentation based on the segmentation data
 * and their configurations. Note: This is a Singleton class and should not be
 * instantiated directly. To trigger a render for all the segmentations, you can use:
 *
 */
class SegmentationRenderingEngine {
  private _needsRender: Set<string> = new Set();
  private _pendingRenderQueue: string[][] = [];
  private _animationFrameSet = false;
  private _animationFrameHandle: number | null = null;
  public hasBeenDestroyed: boolean;
 
  /**
   * Renders the segmentations on the specified viewport or all viewports that has
   * some sort of segmentation representation.
   *
   * @param viewportId - The ID of the viewport to render the segmentations on. If not provided, segmentations will be rendered on all viewports.
   */
  public renderSegmentationsForViewport(viewportId?: string): void {
    const viewportIds = viewportId
      ? [viewportId]
      : this._getViewportIdsForSegmentation();
    this._setViewportsToBeRenderedNextFrame(viewportIds);
  }
 
  /**
   * Renders the segmentation with the specified ID.
   *
   * @param segmentationId - The ID of the segmentation to render.
   */
  public renderSegmentation(segmentationId: string): void {
    const viewportIds = this._getViewportIdsForSegmentation(segmentationId);
    this._setViewportsToBeRenderedNextFrame(viewportIds);
  }
 
  _getAllViewports = () => {
    const renderingEngine = getRenderingEngines();
    return renderingEngine.flatMap((renderingEngine) =>
      renderingEngine.getViewports()
    );
  };
 
  _getViewportIdsForSegmentation(segmentationId?: string): string[] {
    const viewports = this._getAllViewports();
    const viewportIds = [];
 
    for (const viewport of viewports) {
      const viewportId = viewport.id;
 
      if (segmentationId) {
        const segmentationRepresentations = getSegmentationRepresentations(
          viewportId,
          { segmentationId }
        );
 
        if (segmentationRepresentations?.length > 0) {
          viewportIds.push(viewportId);
        }
      } else {
        const segmentationRepresentations =
          getSegmentationRepresentations(viewportId);
 
        Eif (segmentationRepresentations?.length > 0) {
          viewportIds.push(viewportId);
        }
      }
    }
 
    return viewportIds;
  }
 
  /**
   *  _throwIfDestroyed Throws an error if trying to interact with the `RenderingEngine`
   * instance after its `destroy` method has been called.
   */
  private _throwIfDestroyed() {
    Iif (this.hasBeenDestroyed) {
      throw new Error(
        'this.destroy() has been manually called to free up memory, can not longer use this instance. Instead make a new one.'
      );
    }
  }
 
  private _setViewportsToBeRenderedNextFrame(viewportIds: string[]) {
    if (this._animationFrameSet) {
      // If a render is already scheduled, queue this set for after the current one
      this._pendingRenderQueue.push(viewportIds);
      return;
    }
    // Add the viewports to the set of flagged viewports
    viewportIds.forEach((viewportId) => {
      this._needsRender.add(viewportId);
    });
    // Render any flagged viewports
    this._render();
  }
 
  /**
   *  _render Sets up animation frame if necessary
   */
  private _render() {
    // If we have segmentations that need rendering and we have not already
    // set the RAF callback to run on the next frame.
    if (this._needsRender.size > 0 && this._animationFrameSet === false) {
      this._animationFrameHandle = window.requestAnimationFrame(
        this._renderFlaggedSegmentations
      );
 
      // Set the flag that we have already set up the next RAF call.
      this._animationFrameSet = true;
    }
  }
 
  private _renderFlaggedSegmentations = () => {
    this._throwIfDestroyed();
 
    const viewportIds = Array.from(this._needsRender);
 
    viewportIds.forEach((viewportId) => {
      this._triggerRender(viewportId);
    });
 
    // Clear the set of flagged segmentations
    this._needsRender.clear();
 
    // Allow RAF to be called again
    this._animationFrameSet = false;
    this._animationFrameHandle = null;
 
    // If there are pending viewportId sets, schedule the next one
    if (this._pendingRenderQueue.length > 0) {
      const nextViewportIds = this._pendingRenderQueue.shift();
      Eif (nextViewportIds && nextViewportIds.length > 0) {
        this._setViewportsToBeRenderedNextFrame(nextViewportIds);
      }
    }
  };
 
  _triggerRender(viewportId?: string) {
    const segmentationRepresentations =
      getSegmentationRepresentations(viewportId);
 
    if (!segmentationRepresentations?.length) {
      return;
    }
    const { viewport } = getEnabledElementByViewportId(viewportId) || {};
 
    Iif (!viewport) {
      return;
    }
 
    const viewportRenderList = [];
 
    // Render each segmentationData, in each viewport
    const segmentationRenderList = segmentationRepresentations.map(
      (representation: SegmentationRepresentation) => {
        if (representation.type === SegmentationRepresentations.Contour) {
          // if the representation is contour we need to make sure
          // that the planarFreeHandTool is added
          this._addPlanarFreeHandToolIfAbsent(viewport);
        }
 
        const display = renderers[representation.type];
 
        try {
          // @ts-ignore
          const viewportId = display.render(viewport, representation);
          viewportRenderList.push(viewportId);
        } catch (error) {
          console.error(error);
        }
 
        return Promise.resolve({
          segmentationId: representation.segmentationId,
          type: representation.type,
        });
      }
    );
 
    Promise.allSettled(segmentationRenderList).then((results) => {
      const segmentationDetails = results
        .filter((r) => r.status === 'fulfilled')
        .map((r) => r.value);
 
      function onSegmentationRender(evt: Types.EventTypes.ImageRenderedEvent) {
        const { element, viewportId } = evt.detail;
 
        element.removeEventListener(
          Enums.Events.IMAGE_RENDERED,
          onSegmentationRender as EventListener
        );
 
        segmentationDetails.forEach((detail) => {
          const eventDetail: SegmentationRenderedEventDetail = {
            viewportId,
            segmentationId: detail.segmentationId,
            type: detail.type,
          };
 
          triggerEvent(eventTarget, csToolsEvents.SEGMENTATION_RENDERED, {
            ...eventDetail,
          });
        });
      }
 
      // For all viewports, trigger a re-render
      const element = viewport.element;
      element.addEventListener(
        Enums.Events.IMAGE_RENDERED,
        onSegmentationRender as EventListener
      );
 
      // Render the viewport
      viewport.render();
    });
  }
 
  _addPlanarFreeHandToolIfAbsent(viewport) {
    // if it is contour we should check if the cornerstoneTools have the planarFreeHandTool added
    if (!(planarContourToolName in state.tools)) {
      addTool(PlanarFreehandContourSegmentationTool);
    }
    const toolGroup = getToolGroupForViewport(viewport.id);
 
    // check if toolGroup has this tool
    if (!toolGroup.hasTool(planarContourToolName)) {
      toolGroup.addTool(planarContourToolName);
      toolGroup.setToolPassive(planarContourToolName);
    }
  }
}
 
/**
 * It triggers segmentation render for the given viewportIds
 */
function triggerSegmentationRender(viewportId?: string): void {
  segmentationRenderingEngine.renderSegmentationsForViewport(viewportId);
}
 
/**
 * It triggers segmentation render for the given segmentationId
 */
function triggerSegmentationRenderBySegmentationId(
  segmentationId?: string
): void {
  segmentationRenderingEngine.renderSegmentation(segmentationId);
}
 
const segmentationRenderingEngine = new SegmentationRenderingEngine();
export {
  triggerSegmentationRender,
  triggerSegmentationRenderBySegmentationId,
  segmentationRenderingEngine,
};