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

66.66% Statements 10/15
62.5% Branches 5/8
100% Functions 2/2
66.66% Lines 10/15

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                              230x   230x 230x     230x               230x   58650x     58650x       230x         230x   230x    
import { type Types, utilities } from '@cornerstonejs/core';
import { defaultSegmentationStateManager } from './SegmentationStateManager';
import { getNextColorLUTIndex } from './getNextColorLUTIndex';
import CORNERSTONE_COLOR_LUT from '../../constants/COLOR_LUT';
 
/**
 * Add a color LUT to the segmentation state manager
 * @param colorLUT - The color LUT array to add.
 * @param index - The index of the color LUT to add.
 *
 * If no index is provided, the next available index will be used.
 *
 * @returns The index of the color LUT that was added.
 */
export function addColorLUT(colorLUT: Types.ColorLUT, index?: number): number {
  const segmentationStateManager = defaultSegmentationStateManager;
 
  const indexToUse = index ?? getNextColorLUTIndex();
  let colorLUTToUse = [...colorLUT] as Types.ColorLUT;
 
  // Make sure the colorLUT always starts with [0, 0, 0, 0] for the background color
  Iif (!utilities.isEqual(colorLUTToUse[0], [0, 0, 0, 0])) {
    console.warn(
      'addColorLUT: [0, 0, 0, 0] color is not provided for the background color (segmentIndex =0), automatically adding it'
    );
    colorLUTToUse = [[0, 0, 0, 0], ...colorLUTToUse];
  }
 
  // Ensure each color in the LUT has 4 elements (RGBA)
  colorLUTToUse = colorLUTToUse.map((color) => {
    // @ts-expect-error - color.length is not always 3
    Iif (color.length === 3) {
      return [color[0], color[1], color[2], 255] as Types.Color;
    }
    return color as Types.Color;
  });
 
  // Ensure the colorLUT has at least 255 entries
  Iif (colorLUTToUse.length < 255) {
    const missingColorLUTs = CORNERSTONE_COLOR_LUT.slice(colorLUTToUse.length);
    colorLUTToUse = [...colorLUTToUse, ...missingColorLUTs] as Types.ColorLUT;
  }
 
  segmentationStateManager.addColorLUT(colorLUTToUse, indexToUse);
 
  return indexToUse;
}