All files / core/src/RenderingEngine/GenericViewport genericViewportReferenceCompatibility.ts

1.32% Statements 2/151
0% Branches 0/128
0% Functions 0/29
1.33% Lines 2/150

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          128x               128x                                                                                                                                                                                                                      
import { vec3 } from 'gl-matrix';
import type {
  Point3,
  ReferenceCompatibleOptions,
  ViewReference,
} from '../../types';
import type { PlaneRestriction } from '../../types/IViewport';
import imageIdToURI from '../../utilities/imageIdToURI';
import isEqual from '../../utilities/isEqual';
 
export type GenericViewportReferenceContext = {
  allowAnyImageReference?: boolean;
  cameraFocalPoint?: Point3;
  currentImageIdIndex?: number;
  dataId?: string;
  dataIds?: string[];
  dimensionGroupNumber?: number;
  frameOfReferenceUID?: string;
  imageIds?: string[];
  imageURIs?: string[];
  numDimensionGroups?: number;
  viewPlaneNormal?: Point3;
  volumeId?: string;
  volumeIds?: string[];
};
 
/**
 * Standard GenericViewport compatibility predicate for view references.
 */
export function isGenericViewportReferenceViewable(
  viewRef: ViewReference,
  contexts: GenericViewportReferenceContext[],
  options: ReferenceCompatibleOptions = {}
): boolean {
  if (!viewRef) {
    return false;
  }
 
  return contexts.some((context) =>
    isReferenceViewableInContext(viewRef, context, options)
  );
}
 
export function getDimensionGroupReferenceContext(
  value: unknown
): Pick<
  GenericViewportReferenceContext,
  'dimensionGroupNumber' | 'numDimensionGroups'
> {
  const candidate = value as
    | {
        dimensionGroupNumber?: unknown;
        numDimensionGroups?: unknown;
      }
    | undefined;
  const dimensionGroupNumber = toPositiveInteger(
    candidate?.dimensionGroupNumber
  );
  const numDimensionGroups = toPositiveInteger(candidate?.numDimensionGroups);
 
  return {
    dimensionGroupNumber,
    numDimensionGroups,
  };
}
 
function isReferenceViewableInContext(
  viewRef: ViewReference,
  context: GenericViewportReferenceContext,
  options: ReferenceCompatibleOptions
): boolean {
  if (!isFrameOfReferenceCompatible(viewRef, context)) {
    return false;
  }
 
  if (!isDataIdCompatible(viewRef, context)) {
    return false;
  }
 
  if (!isVolumeIdCompatible(viewRef, context)) {
    return false;
  }
 
  if (!isPlaneCompatible(viewRef, context, options)) {
    return false;
  }
 
  if (!isReferencedImageCompatible(viewRef, context, options)) {
    return false;
  }
 
  if (!isDimensionGroupCompatible(viewRef, context, options)) {
    return false;
  }
 
  return isSliceIndexCompatible(viewRef, context, options);
}
 
function isFrameOfReferenceCompatible(
  viewRef: ViewReference,
  context: GenericViewportReferenceContext
): boolean {
  return (
    !viewRef.FrameOfReferenceUID ||
    viewRef.FrameOfReferenceUID === context.frameOfReferenceUID
  );
}
 
function isDataIdCompatible(
  viewRef: ViewReference,
  context: GenericViewportReferenceContext
): boolean {
  if (!viewRef.dataId) {
    return true;
  }
 
  return getContextDataIds(context).includes(viewRef.dataId);
}
 
function isVolumeIdCompatible(
  viewRef: ViewReference,
  context: GenericViewportReferenceContext
): boolean {
  if (!viewRef.volumeId) {
    return true;
  }
 
  return getContextVolumeIds(context).includes(viewRef.volumeId);
}
 
function isPlaneCompatible(
  viewRef: ViewReference,
  context: GenericViewportReferenceContext,
  options: ReferenceCompatibleOptions
): boolean {
  if (viewRef.planeRestriction) {
    return isPlaneRestrictionViewable(
      viewRef.planeRestriction,
      context,
      options
    );
  }
 
  if (!viewRef.viewPlaneNormal) {
    return true;
  }
 
  const { viewPlaneNormal } = context;
 
  if (!viewPlaneNormal) {
    return false;
  }
 
  return (
    isEqual(viewRef.viewPlaneNormal, viewPlaneNormal) ||
    isEqual(
      vec3.negate(vec3.create(), viewPlaneNormal as unknown as vec3) as Point3,
      viewRef.viewPlaneNormal
    ) ||
    Boolean(options.withOrientation)
  );
}
 
function isPlaneRestrictionViewable(
  planeRestriction: PlaneRestriction,
  context: GenericViewportReferenceContext,
  options: ReferenceCompatibleOptions
): boolean {
  if (planeRestriction.FrameOfReferenceUID !== context.frameOfReferenceUID) {
    return false;
  }
 
  if (options.withOrientation) {
    return true;
  }
 
  const { cameraFocalPoint, viewPlaneNormal } = context;
 
  if (!cameraFocalPoint || !viewPlaneNormal) {
    return false;
  }
 
  if (
    planeRestriction.inPlaneVector1 &&
    !isEqual(
      0,
      vec3.dot(
        viewPlaneNormal as unknown as vec3,
        planeRestriction.inPlaneVector1 as unknown as vec3
      )
    )
  ) {
    return false;
  }
 
  if (
    planeRestriction.inPlaneVector2 &&
    !isEqual(
      0,
      vec3.dot(
        viewPlaneNormal as unknown as vec3,
        planeRestriction.inPlaneVector2 as unknown as vec3
      )
    )
  ) {
    return false;
  }
 
  if (options.withNavigation) {
    return true;
  }
 
  const pointVector = vec3.sub(
    vec3.create(),
    planeRestriction.point as unknown as vec3,
    cameraFocalPoint as unknown as vec3
  );
 
  return isEqual(0, vec3.dot(pointVector, viewPlaneNormal as unknown as vec3));
}
 
function isReferencedImageCompatible(
  viewRef: ViewReference,
  context: GenericViewportReferenceContext,
  options: ReferenceCompatibleOptions
): boolean {
  if (
    viewRef.planeRestriction &&
    viewRef.volumeId &&
    getContextVolumeIds(context).includes(viewRef.volumeId)
  ) {
    return true;
  }
 
  const referencedImageURIs = getReferencedImageURIs(viewRef);
 
  if (!referencedImageURIs.length) {
    return true;
  }
 
  const imageURIEntries = getContextImageURIEntries(context);
 
  if (!imageURIEntries.length) {
    return false;
  }
 
  const currentImageIdIndex = context.currentImageIdIndex ?? 0;
  const currentImageURIEntry = imageURIEntries[currentImageIdIndex];
 
  if (imageURIEntryMatches(currentImageURIEntry, referencedImageURIs)) {
    return true;
  }
 
  const foundSliceIndex = imageURIEntries.findIndex((imageURIEntry) =>
    imageURIEntryMatches(imageURIEntry, referencedImageURIs)
  );
 
  if (foundSliceIndex === -1) {
    return false;
  }
 
  if (context.allowAnyImageReference) {
    return true;
  }
 
  if (options.withNavigation) {
    return true;
  }
 
  const rangeEndSliceIndex = getReferencedImageRangeEndIndex(
    imageURIEntries,
    viewRef
  );
 
  if (rangeEndSliceIndex !== undefined) {
    const start = Math.min(foundSliceIndex, rangeEndSliceIndex);
    const end = Math.max(foundSliceIndex, rangeEndSliceIndex);
 
    return start <= currentImageIdIndex && currentImageIdIndex <= end;
  }
 
  return currentImageIdIndex === foundSliceIndex;
}
 
function isDimensionGroupCompatible(
  viewRef: ViewReference,
  context: GenericViewportReferenceContext,
  options: ReferenceCompatibleOptions
): boolean {
  const hasDimensionGroupRestriction =
    typeof viewRef.dimensionGroupNumber !== 'undefined';
  const dimensionGroupNumber = toPositiveInteger(viewRef.dimensionGroupNumber);
 
  if (!hasDimensionGroupRestriction) {
    return true;
  }
 
  if (!dimensionGroupNumber) {
    return false;
  }
 
  if (context.dimensionGroupNumber === dimensionGroupNumber) {
    return true;
  }
 
  if (!options.withNavigation) {
    return false;
  }
 
  return (
    typeof context.numDimensionGroups === 'number' &&
    dimensionGroupNumber <= context.numDimensionGroups
  );
}
 
function isSliceIndexCompatible(
  viewRef: ViewReference,
  context: GenericViewportReferenceContext,
  options: ReferenceCompatibleOptions
): boolean {
  const sliceIndex = viewRef.sliceIndex as
    | number
    | [number, number]
    | undefined;
 
  if (sliceIndex === undefined) {
    return true;
  }
 
  const { currentImageIdIndex } = context;
 
  if (Array.isArray(sliceIndex)) {
    if (typeof currentImageIdIndex === 'number') {
      return (
        sliceIndex[0] <= currentImageIdIndex &&
        currentImageIdIndex <= sliceIndex[1]
      );
    }
 
    return false;
  }
 
  if (!Number.isFinite(sliceIndex)) {
    return false;
  }
 
  if (currentImageIdIndex === sliceIndex) {
    return true;
  }
 
  if (!options.withNavigation) {
    return false;
  }
 
  return isIndexInImageRange(sliceIndex, context.imageIds);
}
 
function getReferencedImageURIs(viewRef: ViewReference): string[] {
  return uniqueStrings([
    viewRef.referencedImageURI,
    ...(viewRef.referencedImageId
      ? getImageIdCompatibleURIs(viewRef.referencedImageId)
      : []),
  ]);
}
 
function getReferencedImageRangeEndIndex(
  imageURIEntries: string[][],
  viewRef: ViewReference
): number | undefined {
  const rangeEndImageURI =
    viewRef.multiSliceReference &&
    getReferencedImageURIs(viewRef.multiSliceReference);
 
  if (!rangeEndImageURI?.length) {
    return;
  }
 
  const rangeEndSliceIndex = imageURIEntries.findIndex((imageURIEntry) =>
    imageURIEntryMatches(imageURIEntry, rangeEndImageURI)
  );
 
  return rangeEndSliceIndex === -1 ? undefined : rangeEndSliceIndex;
}
 
// Cache the compatible URIs for a given imageId. imageId -> URI is a pure,
// stable mapping, so memoizing it avoids re-parsing the same strings on every
// reference-compatibility check (these run once per labelmap image while
// resolving stack segmentation references).
const imageIdCompatibleURIsCache = new Map<string, string[]>();
 
// Cache the per-imageId URI entries for a given imageIds array, keyed on the
// array reference. Reference compatibility is evaluated once per labelmap image
// when resolving stack segmentation references, so without this the full
// imageId -> URI mapping is rebuilt O(labelmapImages x stackImages) times per
// scroll/brush stroke. The imageIds array is replaced (not mutated) when the
// dataset changes, so reference identity is a safe, self-invalidating key.
const imageIdsURIEntriesCache = new WeakMap<string[], string[][]>();
 
function getImageIdsURIEntries(imageIds: string[]): string[][] {
  let entries = imageIdsURIEntriesCache.get(imageIds);
 
  if (!entries) {
    entries = imageIds.map((imageId) => getImageIdCompatibleURIs(imageId));
    imageIdsURIEntriesCache.set(imageIds, entries);
  }
 
  return entries;
}
 
function getContextImageURIEntries(
  context: GenericViewportReferenceContext
): string[][] {
  const baseEntries = context.imageIds?.length
    ? getImageIdsURIEntries(context.imageIds)
    : [];
  const extraImageURIs = context.imageURIs;
 
  if (!extraImageURIs?.length) {
    // Common path. Callers only read the entries, so returning the cached
    // array directly is safe and avoids any per-call allocation.
    return baseEntries;
  }
 
  // Rare path: merge standalone imageURIs not already covered by the cached
  // imageId-derived entries. Copy first so the cached array is never mutated.
  const imageURIEntries = baseEntries.slice();
  const knownImageURIs = new Set<string>();
 
  for (const imageURIEntry of baseEntries) {
    for (const imageURI of imageURIEntry) {
      knownImageURIs.add(imageURI);
    }
  }
 
  for (const imageURI of extraImageURIs) {
    if (!knownImageURIs.has(imageURI)) {
      imageURIEntries.push([imageURI]);
      knownImageURIs.add(imageURI);
    }
  }
 
  return imageURIEntries;
}
 
function getImageIdCompatibleURIs(imageId: string): string[] {
  let uris = imageIdCompatibleURIsCache.get(imageId);
 
  if (!uris) {
    uris = uniqueStrings([imageIdToURI(imageId), getLegacyImageIdURI(imageId)]);
    imageIdCompatibleURIsCache.set(imageId, uris);
  }
 
  return uris;
}
 
function getLegacyImageIdURI(imageId: string): string {
  const colonIndex = imageId.indexOf(':');
 
  return colonIndex === -1 ? imageId : imageId.substring(colonIndex + 1);
}
 
function imageURIEntryMatches(
  imageURIEntry: string[] | undefined,
  referencedImageURIs: string[]
): boolean {
  return Boolean(
    imageURIEntry?.some((imageURI) => referencedImageURIs.includes(imageURI))
  );
}
 
function getContextDataIds(context: GenericViewportReferenceContext): string[] {
  return uniqueStrings([context.dataId, ...(context.dataIds || [])]);
}
 
function getContextVolumeIds(
  context: GenericViewportReferenceContext
): string[] {
  return uniqueStrings([context.volumeId, ...(context.volumeIds || [])]);
}
 
function isIndexInImageRange(index: number, imageIds?: string[]): boolean {
  if (!imageIds?.length) {
    return true;
  }
 
  return index >= 0 && index < imageIds.length;
}
 
function uniqueStrings(values: Array<string | undefined>): string[] {
  return Array.from(
    new Set(
      values.filter((value): value is string => typeof value === 'string')
    )
  );
}
 
function toPositiveInteger(value: unknown): number | undefined {
  if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) {
    return;
  }
 
  return value;
}