All files / core/src/RenderingEngine/GenericViewport/Planar planarVolumePresentation.ts

0% Statements 0/124
0% Branches 0/98
0% Functions 0/18
0% Lines 0/121

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import vtkPiecewiseFunction from '@kitware/vtk.js/Common/DataModel/PiecewiseFunction';
import type vtkImageResliceMapper from '@kitware/vtk.js/Rendering/Core/ImageResliceMapper';
import type vtkImageSlice from '@kitware/vtk.js/Rendering/Core/ImageSlice';
import type { ColormapPublic, VOIRange } from '../../../types';
import { createPlanarRGBTransferFunction } from '../../helpers/planarImageRendering';
import type { PlanarDataPresentation } from './PlanarViewportTypes';
import {
  mapBlendModeToSlabType,
  resolveSlabThickness,
} from './planarVolumeSliceBlendMode';
 
export function applyPlanarVolumePresentation(args: {
  actor: vtkImageSlice;
  mapper: vtkImageResliceMapper;
  defaultVOIRange?: VOIRange;
  props?: PlanarDataPresentation;
}): void {
  const { actor, defaultVOIRange, mapper, props } = args;
  const property = actor.getProperty();
  const voiRange = props?.voiRange ?? defaultVOIRange;
 
  actor.setVisibility(props?.visible === false ? false : true);
 
  if (props?.interpolationType !== undefined) {
    property.setInterpolationType(
      props.interpolationType as Parameters<
        typeof property.setInterpolationType
      >[0]
    );
  }
 
  if (props?.blendMode !== undefined) {
    const slabType = mapBlendModeToSlabType(props.blendMode);
 
    if (slabType !== undefined) {
      mapper.setSlabType(slabType);
    }
  }
 
  mapper.setSlabThickness(resolveSlabThickness(props?.slabThickness));
 
  if (props?.opacity !== undefined) {
    applyVolumeOpacity({
      actor,
      opacity: props.opacity,
      voiRange,
    });
  }
 
  if (!voiRange) {
    return;
  }
 
  const transferFunction = createPlanarRGBTransferFunction({
    colormap: props?.colormap,
    invert: props?.invert,
    voiRange,
  });
 
  property.setUseLookupTableScalarRange(true);
  property.setRGBTransferFunction(0, transferFunction);
 
  applyColormapOpacity({
    actor,
    colormap: props?.colormap,
    voiRange,
  });
}
 
function applyVolumeOpacity(args: {
  actor: vtkImageSlice;
  opacity: number;
  voiRange?: VOIRange;
}): void {
  const { actor, opacity, voiRange } = args;
 
  if (getVolumeNumberOfComponents(actor) < 2) {
    actor.getProperty().setOpacity(opacity);
    return;
  }
 
  const opacityFunction = vtkPiecewiseFunction.newInstance();
  const range = resolveVolumeOpacityRange(actor, voiRange);
 
  opacityFunction.addPoint(range.lower, opacity);
 
  if (range.upper > range.lower) {
    opacityFunction.addPoint(range.upper, opacity);
  }
 
  actor.getProperty().setScalarOpacity(0, opacityFunction);
}
 
function applyColormapOpacity(args: {
  actor: vtkImageSlice;
  colormap?: ColormapPublic;
  voiRange?: VOIRange;
}): void {
  const { actor, colormap, voiRange } = args;
 
  if (!colormap) {
    return;
  }
 
  if (colormap.opacity === undefined && colormap.threshold === undefined) {
    return;
  }
 
  // A `threshold` is an ABSOLUTE scalar value (SUV / pixel value) spanning the
  // full voxel data range, matching the legacy volume path
  // (updateOpacityWithThreshold, which clamps to voxelManager.getRange()) and
  // OHIF's ThresholdMenu (slider bounds = voxel range). An opacity ARRAY's
  // normalized [0,1] values instead map over the VOI range (round-2 fusion
  // behavior). Pick the domain accordingly so a threshold of e.g. 15 SUV is not
  // clamped to a narrow VOI upper (which made everything transparent).
  const range =
    colormap.threshold !== undefined
      ? (getActorScalarRange(actor) ??
        resolveVolumeOpacityRange(actor, voiRange))
      : resolveVolumeOpacityRange(actor, voiRange);
  const opacityFunction = vtkPiecewiseFunction.newInstance();
  const points = buildColormapOpacityPoints({
    colormap,
    range,
    fallbackOpacity: getCurrentMaxOpacity(actor),
  });
 
  points.forEach(([value, opacity]) => {
    opacityFunction.addPoint(value, opacity);
  });
 
  actor.getProperty().setScalarOpacity(0, opacityFunction);
}
 
function buildColormapOpacityPoints(args: {
  colormap: ColormapPublic;
  range: VOIRange;
  fallbackOpacity: number;
}): Array<[number, number]> {
  const { colormap, range, fallbackOpacity } = args;
  const span = range.upper - range.lower;
  const delta = Math.max(Math.abs(span) * 0.001, 1e-3);
  // An opacity ARRAY's `value`s (OpacityMapping.value) are normalized [0,1]
  // fractions of the VOI range (see ColormapPublic docs: the minimum value maps
  // to 0 opacity and the maximum value to 1 opacity). Map them onto the actual
  // scalar range so an overlay opacity array (e.g. a PT/CT fusion colormap)
  // attenuates by scalar value like the numeric opacity path (applyVolumeOpacity),
  // which already spans the VOI range. Without this the points land at raw scalars
  // (0.1 -> 0.1 SUV), making essentially all tissue opaque and hiding the
  // underlying source slice in a fusion.
  const toScalar = (normalized: number) => range.lower + normalized * span;
  // `colormap.threshold`, by contrast, is an ABSOLUTE scalar value (SUV / pixel
  // value): the legacy volume path (updateOpacityWithThreshold) clamps it straight
  // to the voxel range, and OHIF's ThresholdMenu emits values in pixel units. So
  // it is clamped to the range directly, NOT passed through toScalar.
  const threshold =
    colormap.threshold !== undefined
      ? Math.max(range.lower, Math.min(range.upper, colormap.threshold))
      : undefined;
 
  if (Array.isArray(colormap.opacity) && colormap.opacity.length) {
    const sortedPoints = colormap.opacity
      .map(({ opacity, value }) => ({
        opacity: clampToUnit(opacity),
        value: toScalar(value),
      }))
      .sort((a, b) => a.value - b.value);
 
    if (threshold === undefined) {
      return dedupeOpacityPoints(
        sortedPoints.map(({ value, opacity }) => [value, opacity])
      );
    }
 
    const thresholdOpacity = resolvePointOpacityAtValue(
      threshold,
      sortedPoints,
      fallbackOpacity
    );
    const points: Array<[number, number]> = [
      [range.lower, 0],
      [Math.max(range.lower, threshold - delta), 0],
      [threshold, thresholdOpacity],
    ];
 
    sortedPoints.forEach(({ value, opacity }) => {
      if (value > threshold) {
        points.push([value, opacity]);
      }
    });
 
    if (threshold < range.upper) {
      const lastOpacity = points[points.length - 1][1];
 
      if (points[points.length - 1][0] < range.upper) {
        points.push([range.upper, lastOpacity]);
      }
    }
 
    return dedupeOpacityPoints(points);
  }
 
  const opacity =
    colormap.opacity !== undefined
      ? clampToUnit(colormap.opacity as number)
      : clampToUnit(fallbackOpacity);
 
  if (threshold === undefined) {
    return [
      [range.lower, opacity],
      [range.upper, opacity],
    ];
  }
 
  if (threshold >= range.upper) {
    return [
      [range.lower, 0],
      [range.upper, 0],
    ];
  }
 
  return [
    [range.lower, 0],
    [Math.max(range.lower, threshold - delta), 0],
    [threshold, opacity],
    [range.upper, opacity],
  ];
}
 
function resolvePointOpacityAtValue(
  scalarValue: number,
  opacityPoints: Array<{ value: number; opacity: number }>,
  fallbackOpacity: number
): number {
  if (!opacityPoints.length) {
    return clampToUnit(fallbackOpacity);
  }
 
  if (scalarValue <= opacityPoints[0].value) {
    return opacityPoints[0].opacity;
  }
 
  for (let i = 1; i < opacityPoints.length; i++) {
    const previous = opacityPoints[i - 1];
    const current = opacityPoints[i];
 
    if (scalarValue <= current.value) {
      const pointRange = current.value - previous.value;
      const t =
        pointRange > 0 ? (scalarValue - previous.value) / pointRange : 0;
 
      return clampToUnit(
        previous.opacity + (current.opacity - previous.opacity) * t
      );
    }
  }
 
  return opacityPoints[opacityPoints.length - 1].opacity;
}
 
function dedupeOpacityPoints(
  points: Array<[number, number]>
): Array<[number, number]> {
  const deduped: Array<[number, number]> = [];
 
  points.forEach(([value, opacity]) => {
    const lastPoint = deduped[deduped.length - 1];
 
    if (lastPoint && lastPoint[0] === value) {
      lastPoint[1] = opacity;
      return;
    }
 
    deduped.push([value, opacity]);
  });
 
  return deduped;
}
 
function getCurrentMaxOpacity(actor: vtkImageSlice): number {
  const opacityFunction = actor.getProperty().getScalarOpacity(0);
  const opacityValues = opacityFunction?.getDataPointer?.();
 
  if (!opacityValues?.length) {
    return actor.getProperty().getOpacity?.() ?? 1;
  }
 
  let maxOpacity = 0;
 
  for (let i = 1; i < opacityValues.length; i += 2) {
    if (opacityValues[i] > maxOpacity) {
      maxOpacity = opacityValues[i];
    }
  }
 
  return clampToUnit(maxOpacity || 1);
}
 
function clampToUnit(value: number): number {
  return Math.max(0, Math.min(1, value));
}
 
function getVolumeNumberOfComponents(actor: vtkImageSlice): number {
  const mapperInputData = actor.getMapper()?.getInputData?.();
  const scalars = mapperInputData?.getPointData?.()?.getScalars?.();
  const imageDataMetadata = mapperInputData?.get?.('numberOfComponents') as
    | { numberOfComponents?: number }
    | undefined;
 
  return (
    scalars?.getNumberOfComponents?.() ??
    imageDataMetadata?.numberOfComponents ??
    1
  );
}
 
/**
 * Returns the full voxel data range of the volume behind an actor (the streaming
 * volume's voxelManager range, mirroring the legacy threshold path), falling back
 * to the vtk scalar range. Used as the domain for an absolute opacity threshold,
 * which is expressed in voxel/SUV units rather than the (often narrower) VOI range.
 */
function getActorScalarRange(actor: vtkImageSlice): VOIRange | undefined {
  const mapperInputData = actor.getMapper()?.getInputData?.();
  const voxelManager = (
    mapperInputData?.get?.('voxelManager') as
      | { voxelManager?: { getRange?: () => [number, number] } }
      | undefined
  )?.voxelManager;
 
  const voxelRange = voxelManager?.getRange?.();
 
  if (
    voxelRange &&
    Number.isFinite(voxelRange[0]) &&
    Number.isFinite(voxelRange[1]) &&
    voxelRange[1] > voxelRange[0]
  ) {
    return { lower: voxelRange[0], upper: voxelRange[1] };
  }
 
  const scalarRange = mapperInputData
    ?.getPointData?.()
    ?.getScalars?.()
    ?.getRange?.();
 
  if (
    scalarRange &&
    Number.isFinite(scalarRange[0]) &&
    Number.isFinite(scalarRange[1]) &&
    scalarRange[1] > scalarRange[0]
  ) {
    return { lower: scalarRange[0], upper: scalarRange[1] };
  }
 
  return undefined;
}
 
function resolveVolumeOpacityRange(
  actor: vtkImageSlice,
  voiRange?: VOIRange
): VOIRange {
  if (
    voiRange &&
    Number.isFinite(voiRange.lower) &&
    Number.isFinite(voiRange.upper)
  ) {
    return voiRange;
  }
 
  const mapperInputData = actor.getMapper()?.getInputData?.();
  const scalarRange = mapperInputData
    ?.getPointData?.()
    ?.getScalars?.()
    ?.getRange?.();
 
  if (
    scalarRange &&
    Number.isFinite(scalarRange[0]) &&
    Number.isFinite(scalarRange[1])
  ) {
    return {
      lower: scalarRange[0],
      upper: scalarRange[1],
    };
  }
 
  const transferRange = actor
    .getProperty()
    .getRGBTransferFunction(0)
    ?.getRange?.();
 
  if (
    transferRange &&
    Number.isFinite(transferRange[0]) &&
    Number.isFinite(transferRange[1])
  ) {
    return {
      lower: transferRange[0],
      upper: transferRange[1],
    };
  }
 
  return {
    lower: 0,
    upper: 1,
  };
}