@ohif/extension-cornerstone 3.14.0-beta.12 → 3.14.0-beta.120

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (332) hide show
  1. package/dist/915.ohif-extension-cornerstone.umd.js +1 -1
  2. package/dist/ohif-extension-cornerstone.umd.js +1 -5
  3. package/package.json +33 -25
  4. package/src/Viewport/OHIFCornerstoneViewport.css +46 -0
  5. package/src/Viewport/OHIFCornerstoneViewport.tsx +498 -0
  6. package/src/Viewport/Overlays/CornerstoneOverlays.tsx +103 -0
  7. package/src/Viewport/Overlays/CustomizableViewportOverlay.css +25 -0
  8. package/src/Viewport/Overlays/CustomizableViewportOverlay.tsx +469 -0
  9. package/src/Viewport/Overlays/ViewportImageScrollbar.tsx +106 -0
  10. package/src/Viewport/Overlays/ViewportImageSliceLoadingIndicator.tsx +87 -0
  11. package/src/Viewport/Overlays/ViewportOrientationMarkers.css +41 -0
  12. package/src/Viewport/Overlays/ViewportOrientationMarkers.tsx +136 -0
  13. package/src/Viewport/Overlays/ViewportSliceProgressScrollbar/ViewportSliceProgressScrollbar.tsx +195 -0
  14. package/src/Viewport/Overlays/ViewportSliceProgressScrollbar/helpers.ts +46 -0
  15. package/src/Viewport/Overlays/ViewportSliceProgressScrollbar/hooks.ts +383 -0
  16. package/src/Viewport/Overlays/ViewportSliceProgressScrollbar/index.ts +1 -0
  17. package/src/Viewport/Overlays/ViewportSliceProgressScrollbar/types.ts +17 -0
  18. package/src/Viewport/Overlays/utils.ts +66 -0
  19. package/src/commandsModule.ts +2970 -0
  20. package/src/components/AccordionGroup/AccordionGroup.tsx +195 -0
  21. package/src/components/AccordionGroup/index.ts +4 -0
  22. package/src/components/ActiveViewportWindowLevel/ActiveViewportWindowLevel.tsx +23 -0
  23. package/src/components/ActiveViewportWindowLevel/index.js +1 -0
  24. package/src/components/AdvancedRenderingControls/AdvancedRenderingControls.tsx +149 -0
  25. package/src/components/AdvancedRenderingControls/index.ts +1 -0
  26. package/src/components/CinePlayer/CinePlayer.tsx +247 -0
  27. package/src/components/CinePlayer/index.ts +3 -0
  28. package/src/components/DicomUpload/DicomUpload.tsx +111 -0
  29. package/src/components/DicomUpload/DicomUploadProgress.tsx +396 -0
  30. package/src/components/DicomUpload/DicomUploadProgressItem.tsx +119 -0
  31. package/src/components/ExportSegmentationSubMenuItem.tsx +75 -0
  32. package/src/components/FidelityIndicator/FidelityIndicator.tsx +152 -0
  33. package/src/components/FidelityIndicator/index.ts +1 -0
  34. package/src/components/MeasurementItems.tsx +70 -0
  35. package/src/components/MeasurementTableNested.tsx +30 -0
  36. package/src/components/MeasurementsMenu.tsx +84 -0
  37. package/src/components/MeasurementsOrAdditionalFindings.tsx +82 -0
  38. package/src/components/ModalityLoadBadge/ModalityLoadBadge.tsx +171 -0
  39. package/src/components/ModalityLoadBadge/index.ts +1 -0
  40. package/src/components/NavigationComponent/NavigationComponent.tsx +138 -0
  41. package/src/components/NavigationComponent/index.ts +3 -0
  42. package/src/components/OHIFViewportActionCorners.tsx +109 -0
  43. package/src/components/OpacityMenu/OpacityMenu.tsx +54 -0
  44. package/src/components/OpacityMenu/OpacityMenuWrapper.tsx +85 -0
  45. package/src/components/OpacityMenu/index.ts +2 -0
  46. package/src/components/PanelAccordionTrigger.tsx +48 -0
  47. package/src/components/SegmentationToolConfig.tsx +71 -0
  48. package/src/components/SegmentationUtilityButton.tsx +61 -0
  49. package/src/components/SelectItemWithModality.tsx +29 -0
  50. package/src/components/SeriesMeasurements.tsx +90 -0
  51. package/src/components/SeriesSummaryFromDisplaySet.tsx +21 -0
  52. package/src/components/StudyMeasurements.tsx +88 -0
  53. package/src/components/StudyMeasurementsActions.tsx +75 -0
  54. package/src/components/StudySummaryFromMetadata.test.ts +47 -0
  55. package/src/components/StudySummaryFromMetadata.tsx +31 -0
  56. package/src/components/StudySummaryWithActions.tsx +14 -0
  57. package/src/components/ThresholdMenu/ThresholdMenu.tsx +104 -0
  58. package/src/components/ThresholdMenu/ThresholdMenuWrapper.tsx +85 -0
  59. package/src/components/ThresholdMenu/index.ts +2 -0
  60. package/src/components/TrackingStatus/TrackingStatus.tsx +32 -0
  61. package/src/components/TrackingStatus/index.ts +1 -0
  62. package/src/components/VOIManualControlMenu/VOIManualControlMenu.tsx +190 -0
  63. package/src/components/VOIManualControlMenu/VOIManualControlMenuWrapper.tsx +85 -0
  64. package/src/components/VOIManualControlMenu/index.ts +2 -0
  65. package/src/components/ViewportColorbar/ViewportColorbar.tsx +150 -0
  66. package/src/components/ViewportColorbar/ViewportColorbarsContainer.tsx +125 -0
  67. package/src/components/ViewportColorbar/index.ts +5 -0
  68. package/src/components/ViewportDataOverlaySettingMenu/ViewportDataOverlayMenu.tsx +538 -0
  69. package/src/components/ViewportDataOverlaySettingMenu/ViewportDataOverlayMenuWrapper.tsx +91 -0
  70. package/src/components/ViewportDataOverlaySettingMenu/utils.ts +118 -0
  71. package/src/components/ViewportOrientationMenu/ViewportOrientationMenu.tsx +249 -0
  72. package/src/components/ViewportOrientationMenu/ViewportOrientationMenuWrapper.tsx +29 -0
  73. package/src/components/ViewportWindowLevel/ViewportWindowLevel.tsx +261 -0
  74. package/src/components/ViewportWindowLevel/getViewportVolumeHistogram.ts +72 -0
  75. package/src/components/ViewportWindowLevel/histogramWorker.js +97 -0
  76. package/src/components/ViewportWindowLevel/index.js +1 -0
  77. package/src/components/ViewportWindowLevel/utils.ts +176 -0
  78. package/src/components/WindowLevelActionMenu/Colorbar.tsx +30 -0
  79. package/src/components/WindowLevelActionMenu/Colormap.tsx +121 -0
  80. package/src/components/WindowLevelActionMenu/VolumeLighting.tsx +82 -0
  81. package/src/components/WindowLevelActionMenu/VolumeRenderingOptions.tsx +38 -0
  82. package/src/components/WindowLevelActionMenu/VolumeRenderingPresets.tsx +36 -0
  83. package/src/components/WindowLevelActionMenu/VolumeRenderingPresetsContent.tsx +78 -0
  84. package/src/components/WindowLevelActionMenu/VolumeRenderingQuality.tsx +64 -0
  85. package/src/components/WindowLevelActionMenu/VolumeShade.tsx +47 -0
  86. package/src/components/WindowLevelActionMenu/VolumeShift.tsx +92 -0
  87. package/src/components/WindowLevelActionMenu/WindowLevel.tsx +157 -0
  88. package/src/components/WindowLevelActionMenu/WindowLevelActionMenu.tsx +102 -0
  89. package/src/components/WindowLevelActionMenu/WindowLevelActionMenuWrapper.tsx +131 -0
  90. package/src/components/WindowLevelActionMenu/defaultWindowLevelPresets.ts +23 -0
  91. package/src/components/WindowLevelActionMenu/index.ts +11 -0
  92. package/src/components/WindowLevelActionMenu/windowLevelPresetHotkeys.test.ts +19 -0
  93. package/src/components/index.ts +13 -0
  94. package/src/constants/index.ts +13 -0
  95. package/src/customizations/CustomDropdownMenuContent.tsx +106 -0
  96. package/src/customizations/CustomSegmentStatisticsHeader.tsx +140 -0
  97. package/src/customizations/captureViewportModalCustomization.tsx +175 -0
  98. package/src/customizations/colorbarCustomization.ts +93 -0
  99. package/src/customizations/gpuSettingsPresetCustomization.ts +8 -0
  100. package/src/customizations/layoutSelectorCustomization.ts +104 -0
  101. package/src/customizations/measurementsCustomization.ts +124 -0
  102. package/src/customizations/miscCustomization.ts +22 -0
  103. package/src/customizations/modalityColorMapCustomization.ts +23 -0
  104. package/src/customizations/segmentationHydrationCustomization.ts +16 -0
  105. package/src/customizations/segmentationPanelCustomization.tsx +119 -0
  106. package/src/customizations/segmentationToolbarCustomization.ts +964 -0
  107. package/src/customizations/toolGroupToolsCustomization.ts +204 -0
  108. package/src/customizations/toolbarButtonsCustomization.ts +805 -0
  109. package/src/customizations/viewportClickCommandsCustomization.ts +15 -0
  110. package/src/customizations/viewportDownloadWarningCustomization.tsx +6 -0
  111. package/src/customizations/viewportOverlayCustomization.tsx +46 -0
  112. package/src/customizations/viewportScrollbarCustomization.tsx +27 -0
  113. package/src/customizations/viewportToolsCustomization.ts +33 -0
  114. package/src/customizations/volumeRenderingCustomization.ts +14 -0
  115. package/src/customizations/windowLevelPresetsCustomization.ts +5 -0
  116. package/src/enums.ts +9 -0
  117. package/src/getCustomizationModule.tsx +54 -0
  118. package/src/getHangingProtocolModule.ts +47 -0
  119. package/src/getPanelModule.tsx +128 -0
  120. package/src/getSopClassHandlerModule.js +284 -0
  121. package/src/getToolbarModule.tsx +622 -0
  122. package/src/hooks/index.ts +9 -0
  123. package/src/hooks/useActiveViewportSegmentationRepresentations.ts +14 -0
  124. package/src/hooks/useMeasurementTracking.ts +132 -0
  125. package/src/hooks/useMeasurements.ts +104 -0
  126. package/src/hooks/useSegmentations.ts +147 -0
  127. package/src/hooks/useViewportDisplaySets.ts +284 -0
  128. package/src/hooks/useViewportFidelity.ts +243 -0
  129. package/src/hooks/useViewportHover.ts +77 -0
  130. package/src/hooks/useViewportRendering.tsx +868 -0
  131. package/src/hooks/useViewportSegmentations.ts +245 -0
  132. package/src/hps/fourUp.ts +117 -0
  133. package/src/hps/frameView.ts +1581 -0
  134. package/src/hps/main3D.ts +142 -0
  135. package/src/hps/mpr.ts +197 -0
  136. package/src/hps/mprAnd3DVolumeViewport.ts +124 -0
  137. package/src/hps/only3D.ts +70 -0
  138. package/src/hps/primary3D.ts +142 -0
  139. package/src/hps/primaryAxial.ts +114 -0
  140. package/src/id.js +5 -0
  141. package/src/index.tsx +350 -0
  142. package/src/init.tsx +450 -0
  143. package/src/initCineService.ts +75 -0
  144. package/src/initContextMenu.ts +94 -0
  145. package/src/initCornerstoneTools.js +188 -0
  146. package/src/initDoubleClick.ts +82 -0
  147. package/src/initMeasurementService.ts +576 -0
  148. package/src/initStudyPrefetcherService.ts +33 -0
  149. package/src/initWADOImageLoader.js +56 -0
  150. package/src/panels/PanelMeasurement.tsx +84 -0
  151. package/src/panels/PanelSegmentation.tsx +338 -0
  152. package/src/services/ColorbarService/ColorbarService.ts +242 -0
  153. package/src/services/ColorbarService/index.ts +2 -0
  154. package/src/services/CornerstoneCacheService/CornerstoneCacheService.ts +326 -0
  155. package/src/services/CornerstoneCacheService/index.js +3 -0
  156. package/src/services/SegmentationService/RTSTRUCT/mapROIContoursToRTStructData.ts +36 -0
  157. package/src/services/SegmentationService/SegmentationService.test.ts +3727 -0
  158. package/src/services/SegmentationService/SegmentationService.ts +2390 -0
  159. package/src/services/SegmentationService/backends/ISegmentationBackend.ts +102 -0
  160. package/src/services/SegmentationService/backends/ISegmentationServiceInternals.ts +44 -0
  161. package/src/services/SegmentationService/backends/LegacySegmentationBackend.ts +139 -0
  162. package/src/services/SegmentationService/backends/NextSegmentationBackend.ts +159 -0
  163. package/src/services/SegmentationService/backends/index.ts +4 -0
  164. package/src/services/SegmentationService/index.ts +3 -0
  165. package/src/services/SyncGroupService/SyncGroupService.ts +264 -0
  166. package/src/services/SyncGroupService/createHydrateSegmentationSynchronizer.ts +118 -0
  167. package/src/services/SyncGroupService/index.js +3 -0
  168. package/src/services/ToolGroupService/ToolGroupService.test.ts +83 -0
  169. package/src/services/ToolGroupService/ToolGroupService.ts +541 -0
  170. package/src/services/ToolGroupService/index.js +3 -0
  171. package/src/services/ViewedDataService/ViewedDataService.ts +58 -0
  172. package/src/services/ViewedDataService/index.ts +3 -0
  173. package/src/services/ViewportService/CornerstoneViewportService.ts +1814 -0
  174. package/src/services/ViewportService/IViewportService.ts +64 -0
  175. package/src/services/ViewportService/Viewport.ts +372 -0
  176. package/src/services/ViewportService/adapter/IViewportAdapter.contract.test.ts +467 -0
  177. package/src/services/ViewportService/adapter/IViewportAdapter.ts +179 -0
  178. package/src/services/ViewportService/adapter/LegacyViewportAdapter.ts +240 -0
  179. package/src/services/ViewportService/adapter/NextViewportAdapter.ts +241 -0
  180. package/src/services/ViewportService/adapter/getViewportAdapter.ts +62 -0
  181. package/src/services/ViewportService/adapter/index.ts +16 -0
  182. package/src/services/ViewportService/backends/IViewportBackend.ts +195 -0
  183. package/src/services/ViewportService/backends/IViewportOperations.ts +98 -0
  184. package/src/services/ViewportService/backends/IViewportServiceInternals.ts +47 -0
  185. package/src/services/ViewportService/backends/LegacyViewportBackend.ts +264 -0
  186. package/src/services/ViewportService/backends/LegacyViewportOperations.ts +272 -0
  187. package/src/services/ViewportService/backends/NextViewportBackend.ts +673 -0
  188. package/src/services/ViewportService/backends/NextViewportOperations.ts +169 -0
  189. package/src/services/ViewportService/backends/README.md +62 -0
  190. package/src/services/ViewportService/backends/dataIdRegistry.ts +121 -0
  191. package/src/services/ViewportService/backends/viewportOperations.ts +71 -0
  192. package/src/services/ViewportService/constants.ts +3 -0
  193. package/src/state.ts +34 -0
  194. package/src/stores/index.ts +5 -0
  195. package/src/stores/presentationUtils.ts +42 -0
  196. package/src/stores/useLutPresentationStore.ts +166 -0
  197. package/src/stores/usePositionPresentationStore.ts +172 -0
  198. package/src/stores/useSegmentationPresentationStore.test.ts +146 -0
  199. package/src/stores/useSegmentationPresentationStore.ts +417 -0
  200. package/src/stores/useSelectedSegmentationsForViewportStore.ts +85 -0
  201. package/src/stores/useSynchronizersStore.ts +84 -0
  202. package/src/synchronizers/frameViewSynchronizer.ts +52 -0
  203. package/src/tools/CalibrationLineTool.ts +97 -0
  204. package/src/tools/ImageOverlayViewerTool.tsx +279 -0
  205. package/src/tools/OverlayPlaneModuleProvider.ts +40 -0
  206. package/src/tools/WindowLevelTool.test.ts +55 -0
  207. package/src/tools/WindowLevelTool.ts +22 -0
  208. package/src/types/AppTypes.ts +70 -0
  209. package/src/types/Colorbar.ts +114 -0
  210. package/src/types/Colormap.ts +16 -0
  211. package/src/types/CornerstoneCacheService.ts +40 -0
  212. package/src/types/CornerstoneServices.ts +18 -0
  213. package/src/types/Presentation.ts +83 -0
  214. package/src/types/SelectedSegmentationByTypeMap.ts +3 -0
  215. package/src/types/ViewportPresets.ts +53 -0
  216. package/src/types/VolumeLighting.ts +7 -0
  217. package/src/types/VolumeRenderingConfig.ts +8 -0
  218. package/src/types/WindowLevel.ts +5 -0
  219. package/src/types/index.ts +10 -0
  220. package/src/utils/ActiveViewportBehavior.tsx +80 -0
  221. package/src/utils/CornerstoneViewportDownloadForm.tsx +319 -0
  222. package/src/utils/DicomFileUploader.ts +204 -0
  223. package/src/utils/JumpPresets.ts +14 -0
  224. package/src/utils/autoHydrateViewportTypes.ts +69 -0
  225. package/src/utils/colormaps.js +1597 -0
  226. package/src/utils/createSegmentationForViewport.test.ts +93 -0
  227. package/src/utils/createSegmentationForViewport.ts +123 -0
  228. package/src/utils/dicomLoaderService.js +225 -0
  229. package/src/utils/ecgMetadata.test.ts +137 -0
  230. package/src/utils/ecgMetadata.ts +109 -0
  231. package/src/utils/findNearbyToolData.test.ts +125 -0
  232. package/src/utils/findNearbyToolData.ts +21 -0
  233. package/src/utils/findWindowLevelPreset.test.ts +55 -0
  234. package/src/utils/findWindowLevelPreset.ts +46 -0
  235. package/src/utils/generateSegmentationCSVReport.test.ts +324 -0
  236. package/src/utils/generateSegmentationCSVReport.ts +131 -0
  237. package/src/utils/getActiveViewportEnabledElement.test.ts +70 -0
  238. package/src/utils/getActiveViewportEnabledElement.ts +8 -0
  239. package/src/utils/getCenterExtent.test.ts +313 -0
  240. package/src/utils/getCenterExtent.ts +46 -0
  241. package/src/utils/getCornerstoneBlendMode.test.ts +59 -0
  242. package/src/utils/getCornerstoneBlendMode.ts +25 -0
  243. package/src/utils/getCornerstoneOrientation.test.ts +78 -0
  244. package/src/utils/getCornerstoneOrientation.ts +31 -0
  245. package/src/utils/getCornerstoneViewportType.test.ts +169 -0
  246. package/src/utils/getCornerstoneViewportType.ts +88 -0
  247. package/src/utils/getInterleavedFrames.test.ts +85 -0
  248. package/src/utils/getInterleavedFrames.ts +73 -0
  249. package/src/utils/getLegacyViewportType.ts +64 -0
  250. package/src/utils/getNthFrames.test.ts +145 -0
  251. package/src/utils/getNthFrames.ts +31 -0
  252. package/src/utils/getViewportEnabledElement.test.ts +83 -0
  253. package/src/utils/getViewportEnabledElement.ts +8 -0
  254. package/src/utils/getViewportOrientationFromImageOrientationPatient.test.ts +50 -0
  255. package/src/utils/getViewportOrientationFromImageOrientationPatient.ts +56 -0
  256. package/src/utils/hydrationUtils.test.ts +572 -0
  257. package/src/utils/hydrationUtils.ts +197 -0
  258. package/src/utils/imageSliceSync/calculateViewportRegistrations.ts +28 -0
  259. package/src/utils/imageSliceSync/toggleImageSliceSync.ts +101 -0
  260. package/src/utils/index.ts +29 -0
  261. package/src/utils/initGpuSettingsPreset.ts +51 -0
  262. package/src/utils/initViewTiming.test.ts +342 -0
  263. package/src/utils/initViewTiming.ts +52 -0
  264. package/src/utils/initWebWorkerProgressHandler.test.ts +381 -0
  265. package/src/utils/initWebWorkerProgressHandler.ts +110 -0
  266. package/src/utils/interleave.test.ts +304 -0
  267. package/src/utils/interleave.ts +32 -0
  268. package/src/utils/interleaveCenterLoader.test.ts +547 -0
  269. package/src/utils/interleaveCenterLoader.ts +143 -0
  270. package/src/utils/interleaveTopToBottom.test.ts +487 -0
  271. package/src/utils/interleaveTopToBottom.ts +132 -0
  272. package/src/utils/isAnyDisplaySetCommon.ts +18 -0
  273. package/src/utils/isDisplaySetOverlayable.ts +106 -0
  274. package/src/utils/isMeasurementWithinViewport.test.ts +340 -0
  275. package/src/utils/isMeasurementWithinViewport.ts +33 -0
  276. package/src/utils/isReferenceViewable.test.ts +581 -0
  277. package/src/utils/isReferenceViewable.ts +95 -0
  278. package/src/utils/loadDisplaySetData.ts +49 -0
  279. package/src/utils/measurementServiceMappings/Angle.ts +200 -0
  280. package/src/utils/measurementServiceMappings/ArrowAnnotate.ts +176 -0
  281. package/src/utils/measurementServiceMappings/Bidirectional.ts +193 -0
  282. package/src/utils/measurementServiceMappings/CircleROI.ts +227 -0
  283. package/src/utils/measurementServiceMappings/CobbAngle.ts +206 -0
  284. package/src/utils/measurementServiceMappings/EllipticalROI.ts +221 -0
  285. package/src/utils/measurementServiceMappings/Length.ts +206 -0
  286. package/src/utils/measurementServiceMappings/LivewireContour.ts +175 -0
  287. package/src/utils/measurementServiceMappings/PlanarFreehandROI.ts +228 -0
  288. package/src/utils/measurementServiceMappings/Probe.ts +192 -0
  289. package/src/utils/measurementServiceMappings/RectangleROI.ts +225 -0
  290. package/src/utils/measurementServiceMappings/SegmentBidirectional.ts +184 -0
  291. package/src/utils/measurementServiceMappings/SplineROI.ts +227 -0
  292. package/src/utils/measurementServiceMappings/UltrasoundDirectional.ts +214 -0
  293. package/src/utils/measurementServiceMappings/UltrasoundPleuraBLine.ts +179 -0
  294. package/src/utils/measurementServiceMappings/constants/supportedTools.js +21 -0
  295. package/src/utils/measurementServiceMappings/index.ts +3 -0
  296. package/src/utils/measurementServiceMappings/measurementServiceMappingsFactory.ts +324 -0
  297. package/src/utils/measurementServiceMappings/utils/getDisplayUnit.js +3 -0
  298. package/src/utils/measurementServiceMappings/utils/getHandlesFromPoints.js +14 -0
  299. package/src/utils/measurementServiceMappings/utils/getIsLocked.ts +5 -0
  300. package/src/utils/measurementServiceMappings/utils/getIsVisible.ts +6 -0
  301. package/src/utils/measurementServiceMappings/utils/getSOPInstanceAttributes.js +66 -0
  302. package/src/utils/measurementServiceMappings/utils/getValueDisplayString.js +12 -0
  303. package/src/utils/measurementServiceMappings/utils/index.ts +17 -0
  304. package/src/utils/measurementServiceMappings/utils/selection.ts +33 -0
  305. package/src/utils/mpr/getProtocolViewportStructureFromGridViewports.ts +74 -0
  306. package/src/utils/nextViewportPolicies.ts +41 -0
  307. package/src/utils/nextViewports.ts +157 -0
  308. package/src/utils/nthLoader.test.ts +317 -0
  309. package/src/utils/nthLoader.ts +78 -0
  310. package/src/utils/presentations/getViewportPresentations.test.ts +280 -0
  311. package/src/utils/presentations/getViewportPresentations.ts +151 -0
  312. package/src/utils/promptHydrationDialog.test.ts +490 -0
  313. package/src/utils/promptHydrationDialog.ts +197 -0
  314. package/src/utils/promptTimePointScope.tsx +82 -0
  315. package/src/utils/removeViewportSegmentationRepresentations.test.ts +129 -0
  316. package/src/utils/removeViewportSegmentationRepresentations.ts +17 -0
  317. package/src/utils/segmentUtils.test.ts +515 -0
  318. package/src/utils/segmentUtils.ts +46 -0
  319. package/src/utils/segmentationExportUtils.test.ts +100 -0
  320. package/src/utils/segmentationExportUtils.ts +171 -0
  321. package/src/utils/segmentationHandlers.test.ts +614 -0
  322. package/src/utils/segmentationHandlers.ts +164 -0
  323. package/src/utils/setUpAnnotationEventHandlers.ts +26 -0
  324. package/src/utils/setUpSegmentationEventHandlers.test.ts +372 -0
  325. package/src/utils/setUpSegmentationEventHandlers.ts +122 -0
  326. package/src/utils/toggleVOISliceSync.test.ts +606 -0
  327. package/src/utils/toggleVOISliceSync.ts +103 -0
  328. package/src/utils/transitions.test.ts +351 -0
  329. package/src/utils/transitions.ts +300 -0
  330. package/src/utils/updateSegmentationStats.test.ts +942 -0
  331. package/src/utils/updateSegmentationStats.ts +192 -0
  332. package/src/utils/viewportDataShape.ts +85 -0
@@ -0,0 +1,2390 @@
1
+ import {
2
+ cache,
3
+ Enums as csEnums,
4
+ eventTarget,
5
+ geometryLoader,
6
+ getEnabledElementByViewportId,
7
+ imageLoader,
8
+ Types as csTypes,
9
+ utilities as csUtils,
10
+ metaData,
11
+ } from '@cornerstonejs/core';
12
+ import { ViewportType } from '@cornerstonejs/core/enums';
13
+ import { isVolume3DViewportType } from '../../utils/getLegacyViewportType';
14
+
15
+ import {
16
+ Enums as csToolsEnums,
17
+ segmentation as cstSegmentation,
18
+ Types as cstTypes,
19
+ annotation as cstAnnotation,
20
+ } from '@cornerstonejs/tools';
21
+
22
+ import { PubSubService, Types as OHIFTypes } from '@ohif/core';
23
+ import i18n from '@ohif/i18n';
24
+
25
+ import { VOLUME_LOADER_SCHEME } from '../../constants';
26
+ import { mapROIContoursToRTStructData } from './RTSTRUCT/mapROIContoursToRTStructData';
27
+ import { SegmentationPresentation, SegmentationPresentationItem } from '../../types/Presentation';
28
+ import { EasingFunctionEnum, EasingFunctionMap } from '../../utils/transitions';
29
+ import { ViewReference } from '@cornerstonejs/core/types';
30
+ import {
31
+ LegacySegmentationBackend,
32
+ NextSegmentationBackend,
33
+ type ISegmentationBackend,
34
+ type ISegmentationServiceInternals,
35
+ } from './backends';
36
+ // Sanctioned flag read: the SEG data shape (single- vs multi-layer) is fixed at
37
+ // load time, before any target viewport exists, so this one seg-backend dispatch
38
+ // cannot use a per-viewport capability check and reads the session flag instead.
39
+ import { isNextViewportsEnabled } from '../../utils/nextViewports';
40
+ import { isNextViewport } from '../ViewportService/adapter';
41
+
42
+ const { DefaultHistoryMemo } = csUtils.HistoryMemo;
43
+
44
+ const {
45
+ Labelmap: LABELMAP,
46
+ Contour: CONTOUR,
47
+ Surface: SURFACE,
48
+ } = csToolsEnums.SegmentationRepresentations;
49
+
50
+ const {
51
+ getLabelmapImageIds,
52
+ helpers: { convertStackToVolumeLabelmap },
53
+ state: { addColorLUT },
54
+ triggerSegmentationEvents: { triggerSegmentationRepresentationModified },
55
+ } = cstSegmentation;
56
+
57
+ export type SegmentRepresentation = {
58
+ segmentIndex: number;
59
+ color: csTypes.Color;
60
+ opacity: number;
61
+ visible: boolean;
62
+ };
63
+
64
+ export type SegmentationData = cstTypes.Segmentation;
65
+
66
+ export type SegmentationRepresentation = cstTypes.SegmentationRepresentation & {
67
+ viewportId: string;
68
+ id: string;
69
+ label: string;
70
+ fallbackLabel?: string;
71
+ styles: cstTypes.RepresentationStyle;
72
+ segments: {
73
+ [key: number]: SegmentRepresentation;
74
+ };
75
+ };
76
+
77
+ export type SegmentationInfo = {
78
+ segmentation: SegmentationData;
79
+ representation?: SegmentationRepresentation;
80
+ };
81
+
82
+ const EVENTS = {
83
+ SEGMENTATION_MODIFIED: 'event::segmentation_modified',
84
+ // fired when the segmentation is added
85
+ SEGMENTATION_ADDED: 'event::segmentation_added',
86
+ //
87
+ SEGMENTATION_DATA_MODIFIED: 'event::segmentation_data_modified',
88
+ // fired when the segmentation is removed
89
+ SEGMENTATION_REMOVED: 'event::segmentation_removed',
90
+ //
91
+ // fired when segmentation representation is added
92
+ SEGMENTATION_REPRESENTATION_MODIFIED: 'event::segmentation_representation_modified',
93
+ // fired when segmentation representation is removed
94
+ SEGMENTATION_REPRESENTATION_REMOVED: 'event::segmentation_representation_removed',
95
+ //
96
+ // LOADING EVENTS
97
+ // fired when the active segment is loaded in SEG or RTSTRUCT
98
+ SEGMENT_LOADING_COMPLETE: 'event::segment_loading_complete',
99
+ // loading completed for all segments
100
+ SEGMENTATION_LOADING_COMPLETE: 'event::segmentation_loading_complete',
101
+ // fired when a contour annotation cut merge process is completed
102
+ SEGMENTATION_ANNOTATION_CUT_MERGE_PROCESS_COMPLETED:
103
+ 'event::annotation_cut_merge_process_completed',
104
+ SEGMENTATION_STYLE_MODIFIED: 'event::segmentation_style_modified',
105
+ };
106
+
107
+ const VALUE_TYPES = {};
108
+
109
+ // A selected segment's highlight: animating, or finished and still selected.
110
+ type SegmentHighlight = {
111
+ segmentationId: string;
112
+ segmentIndex: number;
113
+ type: csToolsEnums.SegmentationRepresentations;
114
+ state: 'highlighting' | 'selected';
115
+ };
116
+
117
+ const segmentHighlightKey = (
118
+ segmentationId: string,
119
+ segmentIndex: number,
120
+ type: csToolsEnums.SegmentationRepresentations
121
+ ) => `${segmentationId}:${segmentIndex}:${type}`;
122
+
123
+ class SegmentationService extends PubSubService implements ISegmentationServiceInternals {
124
+ static REGISTRATION = {
125
+ name: 'segmentationService',
126
+ altName: 'SegmentationService',
127
+ create: ({ servicesManager }: OHIFTypes.Extensions.ExtensionParams): SegmentationService => {
128
+ return new SegmentationService({ servicesManager });
129
+ },
130
+ };
131
+
132
+ private _segmentationIdToColorLUTIndexMap: Map<string, number>;
133
+ private _segmentationGroupStatsMap: Map<string, any>;
134
+ private readonly _legacySegBackend: ISegmentationBackend;
135
+ private readonly _nextSegBackend: ISegmentationBackend;
136
+ readonly servicesManager: AppTypes.ServicesManager;
137
+ // The highlighted segment's animation state, keyed by segmentHighlightKey. A
138
+ // segment that is not selected has no entry. Each highlight runs as a
139
+ // requestAnimationFrame loop that stops as soon as its entry is no longer current.
140
+ private _segmentHighlights = new Map<string, SegmentHighlight>();
141
+ readonly EVENTS = EVENTS;
142
+
143
+ constructor({ servicesManager }) {
144
+ super(EVENTS);
145
+
146
+ this._segmentationIdToColorLUTIndexMap = new Map();
147
+
148
+ this.servicesManager = servicesManager;
149
+
150
+ this._segmentationGroupStatsMap = new Map();
151
+
152
+ // Segmentation backend twins (mirror the viewport backend family). Routed PER
153
+ // VIEWPORT via _segBackend() using the adapter's isNextViewport predicate,
154
+ // because a flag-on session can mix native and legacy viewports. Both are
155
+ // constructed eagerly:
156
+ // per-viewport dispatch has no per-session flag to defer on, and the twins read
157
+ // state at call time (post-init), not at construction.
158
+ this._legacySegBackend = new LegacySegmentationBackend(this);
159
+ this._nextSegBackend = new NextSegmentationBackend();
160
+ }
161
+
162
+ /**
163
+ * Picks the segmentation backend lane for a specific viewport: the native
164
+ * ("next") twin for a raw GenericViewport (PlanarViewport), the legacy twin
165
+ * otherwise. Mirrors viewportOperations' per-viewport dispatch.
166
+ */
167
+ private _segBackend(viewport: csTypes.IViewport): ISegmentationBackend {
168
+ return isNextViewport(viewport) ? this._nextSegBackend : this._legacySegBackend;
169
+ }
170
+
171
+ public onModeEnter(): void {
172
+ this._initSegmentationService();
173
+ }
174
+
175
+ public onModeExit(): void {
176
+ this.destroy();
177
+ }
178
+
179
+ /**
180
+ * Retrieves a segmentation by its ID.
181
+ *
182
+ * @param segmentationId - The unique identifier of the segmentation to retrieve.
183
+ * @returns The segmentation object if found, or undefined if not found.
184
+ *
185
+ * @remarks
186
+ * This method directly accesses the cornerstone tools segmentation state to fetch
187
+ * the segmentation data. It's useful when you need to access specific properties
188
+ * or perform operations on a particular segmentation.
189
+ */
190
+ public getSegmentation(segmentationId: string): cstTypes.Segmentation | undefined {
191
+ return cstSegmentation.state.getSegmentation(segmentationId);
192
+ }
193
+
194
+ /**
195
+ * Retrieves all segmentations from the cornerstone tools segmentation state.
196
+ *
197
+ * @returns An array of all segmentations currently stored in the state
198
+ *
199
+ * @remarks
200
+ * This is a convenience method that directly accesses the cornerstone tools
201
+ * segmentation state to get all available segmentations. It returns the raw
202
+ * segmentation objects without any additional processing or filtering.
203
+ */
204
+ public getSegmentations(): cstTypes.Segmentation[] | [] {
205
+ return cstSegmentation.state.getSegmentations();
206
+ }
207
+
208
+ public getPresentation(viewportId: string): SegmentationPresentation {
209
+ const segmentationPresentations: SegmentationPresentation = [];
210
+ const segmentationsMap = new Map<string, SegmentationPresentationItem>();
211
+
212
+ const representations = this.getSegmentationRepresentations(viewportId);
213
+ for (const representation of representations) {
214
+ if (!representation) {
215
+ continue;
216
+ }
217
+
218
+ const { segmentationId, type } = representation;
219
+
220
+ segmentationsMap.set(segmentationId, {
221
+ segmentationId,
222
+ type,
223
+ hydrated: true,
224
+ config: representation.config || {},
225
+ });
226
+ }
227
+
228
+ // Check inside the removedDisplaySetAndRepresentationMaps to see if any of the representations are not hydrated
229
+ // const hydrationMap = this._segmentationRepresentationHydrationMaps.get(presentationId);
230
+
231
+ // if (hydrationMap) {
232
+ // hydrationMap.forEach(rep => {
233
+ // segmentationsMap.set(rep.segmentationId, {
234
+ // segmentationId: rep.segmentationId,
235
+ // type: rep.type,
236
+ // hydrated: rep.hydrated,
237
+ // config: rep.config || {},
238
+ // });
239
+ // });
240
+ // }
241
+
242
+ // // Convert the Map to an array
243
+ segmentationPresentations.push(...segmentationsMap.values());
244
+
245
+ return segmentationPresentations;
246
+ }
247
+
248
+ public getRepresentationsForSegmentation(
249
+ segmentationId: string
250
+ ): { viewportId: string; representations: any[] }[] {
251
+ const representations =
252
+ cstSegmentation.state.getSegmentationRepresentationsBySegmentationId(segmentationId);
253
+
254
+ return representations;
255
+ }
256
+
257
+ /**
258
+ * Retrieves segmentation representations (labelmap, contour, surface) based on specified criteria.
259
+ *
260
+ * @param viewportId - The ID of the viewport.
261
+ * @param specifier - An object containing optional `segmentationId` and `type` to filter the representations.
262
+ * @returns An array of `SegmentationRepresentation` matching the criteria, or an empty array if none are found.
263
+ *
264
+ * @remarks
265
+ * This method filters the segmentation representations according to the provided `specifier`:
266
+ * - **No `segmentationId` or `type` provided**: Returns all representations associated with the given `viewportId`.
267
+ * - **Only `segmentationId` provided**: Returns all representations with that `segmentationId`, regardless of `viewportId`.
268
+ * - **Only `type` provided**: Returns all representations of that `type` associated with the given `viewportId`.
269
+ * - **Both `segmentationId` and `type` provided**: Returns representations matching both criteria, regardless of `viewportId`.
270
+ */
271
+ public getSegmentationRepresentations(
272
+ viewportId: string,
273
+ specifier: {
274
+ segmentationId?: string;
275
+ type?: csToolsEnums.SegmentationRepresentations;
276
+ } = {}
277
+ ): SegmentationRepresentation[] {
278
+ // Get all representations for the viewportId
279
+ const representations = cstSegmentation.state.getSegmentationRepresentations(
280
+ viewportId,
281
+ specifier
282
+ );
283
+
284
+ // Map to our SegmentationRepresentation type
285
+ const ohifRepresentations = representations.map(repr =>
286
+ this._toOHIFSegmentationRepresentation(viewportId, repr)
287
+ );
288
+
289
+ return ohifRepresentations;
290
+ }
291
+
292
+ public destroy = () => {
293
+ eventTarget.removeEventListener(
294
+ csToolsEnums.Events.SEGMENTATION_MODIFIED,
295
+ this._onSegmentationModifiedFromSource
296
+ );
297
+
298
+ eventTarget.removeEventListener(
299
+ csToolsEnums.Events.SEGMENTATION_REMOVED,
300
+ this._onSegmentationRemovedFromSource
301
+ );
302
+
303
+ eventTarget.removeEventListener(
304
+ csToolsEnums.Events.SEGMENTATION_DATA_MODIFIED,
305
+ this._onSegmentationDataModifiedFromSource
306
+ );
307
+
308
+ eventTarget.removeEventListener(
309
+ csToolsEnums.Events.SEGMENTATION_REPRESENTATION_MODIFIED,
310
+ this._onSegmentationRepresentationModifiedFromSource
311
+ );
312
+
313
+ eventTarget.removeEventListener(
314
+ csToolsEnums.Events.SEGMENTATION_REPRESENTATION_ADDED,
315
+ this._onSegmentationRepresentationModifiedFromSource
316
+ );
317
+
318
+ eventTarget.removeEventListener(
319
+ csToolsEnums.Events.SEGMENTATION_REPRESENTATION_REMOVED,
320
+ this._onSegmentationRepresentationRemovedFromSource
321
+ );
322
+
323
+ eventTarget.removeEventListener(
324
+ csToolsEnums.Events.SEGMENTATION_ADDED,
325
+ this._onSegmentationAddedFromSource
326
+ );
327
+
328
+ this.reset();
329
+ };
330
+
331
+ public async addSegmentationRepresentation(
332
+ viewportId: string,
333
+ {
334
+ segmentationId,
335
+ predecessorImageId,
336
+ type,
337
+ config,
338
+ suppressEvents = false,
339
+ }: {
340
+ segmentationId: string;
341
+ predecessorImageId?: string;
342
+ type?: csToolsEnums.SegmentationRepresentations;
343
+ config?: {
344
+ blendMode?: csEnums.BlendModes;
345
+ useSliceRendering?: boolean;
346
+ };
347
+ suppressEvents?: boolean;
348
+ }
349
+ ): Promise<void> {
350
+ const segmentation = this.getSegmentation(segmentationId);
351
+
352
+ if (!segmentation) {
353
+ console.warn(
354
+ `addSegmentationRepresentation: segmentation "${segmentationId}" is not in state yet`
355
+ );
356
+ return;
357
+ }
358
+
359
+ if (!segmentation.predecessorImageId && predecessorImageId) {
360
+ segmentation.predecessorImageId = predecessorImageId;
361
+ }
362
+ const csViewport = this.getAndValidateViewport(viewportId);
363
+
364
+ if (!csViewport) {
365
+ return;
366
+ }
367
+
368
+ // A stale/invalid segmentationId yields no segmentation; fail fast with a clear
369
+ // message instead of dereferencing representationData deep inside the backend
370
+ // classification below.
371
+ if (!segmentation) {
372
+ throw new Error(
373
+ `SegmentationService: cannot add representation - segmentation "${segmentationId}" not found.`
374
+ );
375
+ }
376
+
377
+ const colorLUTIndex = this._segmentationIdToColorLUTIndexMap.get(segmentationId);
378
+
379
+ let isConverted = false;
380
+
381
+ const defaultRepresentationType: csToolsEnums.SegmentationRepresentations =
382
+ isVolume3DViewportType(csViewport) ? SURFACE : LABELMAP;
383
+ let representationTypeToUse = type || defaultRepresentationType;
384
+
385
+ if (representationTypeToUse === LABELMAP) {
386
+ ({ representationTypeToUse, isConverted } = await this._segBackend(
387
+ csViewport
388
+ ).classifyAndPrepareLabelmapAdd(
389
+ csViewport,
390
+ segmentation,
391
+ viewportId,
392
+ segmentationId,
393
+ representationTypeToUse
394
+ ));
395
+
396
+ // Overlap precondition: an overlapping SEG is registered as multiple labelmap
397
+ // layers, but cornerstone only stacks them (slice rendering) when the viewport
398
+ // renders as a volume slice (VTK_VOLUME_SLICE) — i.e. an MPR/volume viewport. On
399
+ // a stack/acquisition viewport the render plan falls back to a single layer, so
400
+ // only the primary group is visible. Warn rather than fail silently.
401
+ const labelmapLayers = segmentation?.representationData?.[LABELMAP]?.labelmaps;
402
+ const isOverlapping = labelmapLayers && Object.keys(labelmapLayers).length > 1;
403
+ if (
404
+ isOverlapping &&
405
+ isNextViewport(csViewport) &&
406
+ !csUtils.viewportIsInVolumeMode(csViewport)
407
+ ) {
408
+ console.warn(
409
+ `Overlapping segmentation ${segmentationId} has multiple labelmap layers, but ` +
410
+ `viewport ${viewportId} does not render as a volume slice (VTK_VOLUME_SLICE); ` +
411
+ `only the primary layer will be visible. Display the segmentation in an ` +
412
+ `MPR/volume layout to see all overlapping segments.`
413
+ );
414
+ }
415
+ }
416
+
417
+ await this._addSegmentationRepresentation(
418
+ viewportId,
419
+ segmentationId,
420
+ representationTypeToUse,
421
+ colorLUTIndex,
422
+ isConverted,
423
+ config
424
+ );
425
+
426
+ if (!suppressEvents) {
427
+ this._broadcastEvent(this.EVENTS.SEGMENTATION_REPRESENTATION_MODIFIED, { segmentationId });
428
+ }
429
+ }
430
+
431
+ /**
432
+ * Creates an labelmap segmentation for a given display set
433
+ *
434
+ * @param displaySet - The display set to create the segmentation for.
435
+ * @param options - Optional parameters for creating the segmentation.
436
+ * @param options.segmentationId - Custom segmentation ID. If not provided, a UUID will be generated.
437
+ * @param options.FrameOfReferenceUID - Frame of reference UID for the segmentation.
438
+ * @param options.label - Label for the segmentation.
439
+ * @returns A promise that resolves to the created segmentation ID.
440
+ */
441
+ public async createLabelmapForDisplaySet(
442
+ displaySet: AppTypes.DisplaySet,
443
+ options?: {
444
+ segmentationId?: string;
445
+ segments?: { [segmentIndex: number]: Partial<cstTypes.Segment> };
446
+ FrameOfReferenceUID?: string;
447
+ label?: string;
448
+ /** The caller invented the label, so the user has not chosen a name. */
449
+ labelIsGenerated?: boolean;
450
+ /**
451
+ * For a 4D display set. 'all' (the default) makes one 3D labelmap that
452
+ * all time points share; 'each' makes a labelmap for each time point.
453
+ */
454
+ timePointScope?: 'all' | 'each';
455
+ /** For 'all': the 0-based time point of the labelmap. Default: the middle one. */
456
+ timePointIndex?: number;
457
+ }
458
+ ): Promise<string> {
459
+ return this._createSegmentationForDisplaySet(displaySet, LABELMAP, options);
460
+ }
461
+
462
+ public async createContourForDisplaySet(
463
+ displaySet: AppTypes.DisplaySet,
464
+ options?: {
465
+ segmentationId?: string;
466
+ segments?: { [segmentIndex: number]: Partial<cstTypes.Segment> };
467
+ FrameOfReferenceUID?: string;
468
+ label?: string;
469
+ /** The caller invented the label, so the user has not chosen a name. */
470
+ labelIsGenerated?: boolean;
471
+ }
472
+ ): Promise<string> {
473
+ return this._createSegmentationForDisplaySet(displaySet, CONTOUR, options);
474
+ }
475
+
476
+ /**
477
+ * Private method to create segmentation for a display set with the specified type
478
+ *
479
+ * @param displaySet - The display set to create the segmentation for
480
+ * @param segmentationType - The type of segmentation (SegmentationRepresentations enum)
481
+ * @param options - Optional parameters for creating the segmentation
482
+ * @returns A promise that resolves to the created segmentation ID
483
+ */
484
+ private async _createSegmentationForDisplaySet(
485
+ displaySet: AppTypes.DisplaySet,
486
+ segmentationType: SegmentationRepresentations,
487
+ options?: {
488
+ segmentationId?: string;
489
+ segments?: { [segmentIndex: number]: Partial<cstTypes.Segment> };
490
+ FrameOfReferenceUID?: string;
491
+ label?: string;
492
+ /** The caller invented the label, so the user has not chosen a name. */
493
+ labelIsGenerated?: boolean;
494
+ timePointScope?: 'all' | 'each';
495
+ timePointIndex?: number;
496
+ }
497
+ ): Promise<string> {
498
+ // Todo: random does not makes sense, make this better, like
499
+ // labelmap 1, 2, 3 etc
500
+ const segmentationId = options?.segmentationId ?? `${csUtils.uuidv4()}`;
501
+
502
+ // A 4D segmentation is one 3D labelmap of one time point, which shows on
503
+ // every time point. A labelmap with 'each' has one labelmap image for each
504
+ // frame of every time point; Cornerstone tools shows and edits the images
505
+ // of the time point on display, and RLE keeps the many images small.
506
+ const timePoints = displaySet.isDynamicVolume && displaySet.dynamicVolumeInfo?.timePoints;
507
+ const eachTimePoint =
508
+ timePoints && segmentationType === LABELMAP && options?.timePointScope === 'each';
509
+ const referenceImageIds =
510
+ timePoints && !eachTimePoint
511
+ ? timePoints[options?.timePointIndex ?? Math.floor(timePoints.length / 2)]
512
+ : displaySet.imageIds;
513
+ const derivedImages = await (eachTimePoint
514
+ ? imageLoader.createAndCacheDerivedLabelmapImages(referenceImageIds, {
515
+ voxelRepresentation: csEnums.VoxelManagerEnum.RLE,
516
+ })
517
+ : imageLoader.createAndCacheDerivedLabelmapImages(referenceImageIds));
518
+
519
+ const segs = this.getSegmentations();
520
+ const label = options?.label || `Segmentation ${segs.length + 1}`;
521
+
522
+ const segImageIds = derivedImages.map(image => image.imageId);
523
+
524
+ const segmentationPublicInput: cstTypes.SegmentationPublicInput = {
525
+ segmentationId,
526
+ representation: {
527
+ type: segmentationType,
528
+ data: {
529
+ imageIds: segImageIds,
530
+ // referencedVolumeId: this._getVolumeIdForDisplaySet(displaySet),
531
+ referencedImageIds: referenceImageIds,
532
+ },
533
+ },
534
+ config: {
535
+ label,
536
+ // Explicit, because `label` below always has a value by this point.
537
+ labelIsGenerated: options?.labelIsGenerated ?? !options?.label,
538
+ fallbackLabel: `S:${displaySet.SeriesNumber} ${displaySet.Modality}`,
539
+ segments:
540
+ options?.segments && Object.keys(options.segments).length > 0
541
+ ? options.segments
542
+ : {
543
+ 1: {
544
+ label: `${i18n.t('Segment')} 1`,
545
+ active: true,
546
+ },
547
+ },
548
+ cachedStats: {
549
+ info: `S${displaySet.SeriesNumber}: ${displaySet.SeriesDescription}`,
550
+ },
551
+ },
552
+ };
553
+
554
+ // Create a dedicated color LUT up front and remember its index so that every
555
+ // representation of this segmentation (one per viewport) reuses the same LUT.
556
+ // Otherwise each viewport would get its own default LUT copy and editing a
557
+ // segment color on one viewport would not be reflected on the others (the
558
+ // segment color appears to revert to the default when interacting elsewhere).
559
+ // The caller may pass the id of an existing segmentation, which this method
560
+ // updates rather than replaces; keep its LUT so representations already
561
+ // rendering it don't diverge from the ones created afterwards.
562
+ if (!this._segmentationIdToColorLUTIndexMap.has(segmentationId)) {
563
+ const colorLUTIndex = addColorLUT([[0, 0, 0, 0]] as csTypes.ColorLUT);
564
+ this._segmentationIdToColorLUTIndexMap.set(segmentationId, colorLUTIndex);
565
+ }
566
+
567
+ this.addOrUpdateSegmentation(segmentationPublicInput);
568
+ return segmentationId;
569
+ }
570
+
571
+ public async createSegmentationForSEGDisplaySet(
572
+ segDisplaySet,
573
+ options: {
574
+ segmentationId?: string;
575
+ type: csToolsEnums.SegmentationRepresentations;
576
+ } = {
577
+ type: LABELMAP,
578
+ }
579
+ ): Promise<string> {
580
+ const { type } = options;
581
+ let { segmentationId } = options;
582
+ const { labelMapImages } = segDisplaySet;
583
+
584
+ if (type !== LABELMAP) {
585
+ throw new Error('Only labelmap type is supported for SEG display sets right now');
586
+ }
587
+
588
+ if (!labelMapImages || !labelMapImages.length) {
589
+ throw new Error('SEG reading failed');
590
+ }
591
+
592
+ segmentationId = segmentationId ?? segDisplaySet.displaySetInstanceUID;
593
+ const referencedDisplaySetInstanceUID = segDisplaySet.referencedDisplaySetInstanceUID;
594
+ const referencedDisplaySet = this.servicesManager.services.displaySetService.getDisplaySetByUID(
595
+ referencedDisplaySetInstanceUID
596
+ );
597
+
598
+ const images = referencedDisplaySet.instances;
599
+
600
+ if (!images.length) {
601
+ throw new Error('No instances were provided for the referenced display set of the SEG');
602
+ }
603
+
604
+ // Use the same imageIds as SEG parse (_loadSegments stores these on segDisplaySet).
605
+ const imageIds =
606
+ segDisplaySet.referencedImageIds ||
607
+ (referencedDisplaySet.imageIds as string[] | undefined) ||
608
+ images.map(image => image.imageId);
609
+
610
+ if (!imageIds?.length) {
611
+ throw new Error('referencedDisplaySet has no imageIds for SEG');
612
+ }
613
+ const derivedImages = labelMapImages?.flat();
614
+ const derivedImageIds = derivedImages.map(image => image.imageId);
615
+
616
+ // Note: instance runtime props (frameNumber, imageId, url, ...) are
617
+ // intentionally non-enumerable, so this spread deliberately does NOT copy
618
+ // them — frameNumber must not be carried onto these derived image entries.
619
+ // Read such props off the original instance, never off a copy.
620
+ segDisplaySet.images = derivedImages.map(image => ({
621
+ ...image,
622
+ ...metaData.get('instance', image.referencedImageId),
623
+ }));
624
+
625
+ segDisplaySet.imageIds = derivedImageIds;
626
+
627
+ // We should parse the segmentation as separate slices to support overlapping segments.
628
+ // This parsing should occur in the CornerstoneJS library adapters.
629
+ // For now, we use the volume returned from the library and chop it here.
630
+ let firstSegmentedSliceImageId = null;
631
+ for (let i = 0; i < derivedImages.length; i++) {
632
+ const voxelManager = derivedImages[i].voxelManager as csTypes.IVoxelManager<number>;
633
+ const scalarData = voxelManager.getScalarData();
634
+ voxelManager.setScalarData(scalarData);
635
+
636
+ // Check if this slice has any non-zero voxels and we haven't found one yet
637
+ if (!firstSegmentedSliceImageId && scalarData.some(value => value !== 0)) {
638
+ firstSegmentedSliceImageId = derivedImages[i].referencedImageId;
639
+ }
640
+ }
641
+
642
+ // assign the first non zero voxel image id to the segDisplaySet
643
+ segDisplaySet.firstSegmentedSliceImageId = firstSegmentedSliceImageId;
644
+
645
+ const segmentsInfo = segDisplaySet.segMetadata.data;
646
+
647
+ const segments: { [segmentIndex: string]: cstTypes.Segment } = {};
648
+ const colorLUT = [];
649
+
650
+ segmentsInfo.forEach((segmentInfo, index) => {
651
+ if (index === 0) {
652
+ colorLUT.push([0, 0, 0, 0]);
653
+ return;
654
+ }
655
+
656
+ const {
657
+ SegmentedPropertyCategoryCodeSequence,
658
+ SegmentNumber,
659
+ SegmentLabel,
660
+ SegmentAlgorithmType,
661
+ SegmentAlgorithmName,
662
+ SegmentedPropertyTypeCodeSequence,
663
+ rgba,
664
+ } = segmentInfo;
665
+
666
+ colorLUT.push(rgba);
667
+
668
+ const segmentIndex = Number(SegmentNumber);
669
+
670
+ const centroid = segDisplaySet.centroids?.get(index);
671
+ const imageCentroidXYZ = centroid?.image || { x: 0, y: 0, z: 0 };
672
+ const worldCentroidXYZ = centroid?.world || { x: 0, y: 0, z: 0 };
673
+
674
+ segments[segmentIndex] = {
675
+ segmentIndex,
676
+ label: SegmentLabel || `Segment ${SegmentNumber}`,
677
+ locked: false,
678
+ active: false,
679
+ cachedStats: {
680
+ center: {
681
+ image: [imageCentroidXYZ.x, imageCentroidXYZ.y, imageCentroidXYZ.z],
682
+ world: [worldCentroidXYZ.x, worldCentroidXYZ.y, worldCentroidXYZ.z],
683
+ },
684
+ modifiedTime: segDisplaySet.SeriesDate,
685
+ category: SegmentedPropertyCategoryCodeSequence
686
+ ? SegmentedPropertyCategoryCodeSequence.CodeMeaning
687
+ : '',
688
+ type: SegmentedPropertyTypeCodeSequence
689
+ ? SegmentedPropertyTypeCodeSequence.CodeMeaning
690
+ : '',
691
+ algorithmType: SegmentAlgorithmType,
692
+ algorithmName: SegmentAlgorithmName,
693
+ },
694
+ };
695
+ });
696
+
697
+ const colorLUTIndex = addColorLUT(colorLUT);
698
+ this._segmentationIdToColorLUTIndexMap.set(segmentationId, colorLUTIndex);
699
+
700
+ // Build the segmentation input via the backend twin. At SEG-load there is no
701
+ // target viewport yet, so the lane is chosen by the session flag (the one
702
+ // viewport-less seg-backend dispatch): the next twin registers overlapping SEGs
703
+ // as multiple labelmap layers (slice rendering); the legacy twin keeps the single
704
+ // flattened layer (byte-identical).
705
+ const segBackend = isNextViewportsEnabled() ? this._nextSegBackend : this._legacySegBackend;
706
+ const seg = segBackend.assembleSegmentationDataForSEG({
707
+ segmentationId,
708
+ segDisplaySet,
709
+ derivedImageIds,
710
+ referencedImageIds: imageIds as string[],
711
+ label: segDisplaySet.SeriesDescription,
712
+ fallbackLabel: `S:${segDisplaySet.SeriesNumber} ${segDisplaySet.Modality}`,
713
+ segments,
714
+ });
715
+
716
+ segDisplaySet.isLoaded = true;
717
+
718
+ // Add the segmentation to cornerstone state BEFORE broadcasting that loading is
719
+ // complete. Subscribers (e.g. CornerstoneViewportService) react synchronously and
720
+ // call addSegmentationRepresentation, which now early-returns when the segmentation
721
+ // is not yet in cornerstone state. Broadcasting first would make that guard always
722
+ // fire on initial load, silently preventing the representation from being attached.
723
+ this.addOrUpdateSegmentation(seg);
724
+
725
+ this._broadcastEvent(EVENTS.SEGMENTATION_LOADING_COMPLETE, {
726
+ segmentationId,
727
+ segDisplaySet,
728
+ });
729
+
730
+ return segmentationId;
731
+ }
732
+
733
+ public async createSegmentationForRTDisplaySet(
734
+ rtDisplaySet,
735
+ options: {
736
+ segmentationId?: string;
737
+ type: csToolsEnums.SegmentationRepresentations;
738
+ } = {
739
+ type: CONTOUR,
740
+ }
741
+ ): Promise<string> {
742
+ const { type } = options;
743
+ let { segmentationId } = options;
744
+
745
+ // Currently, only contour representation is supported for RT display
746
+ if (type !== CONTOUR) {
747
+ throw new Error('Only contour type is supported for RT display sets right now');
748
+ }
749
+
750
+ // Assign segmentationId if not provided
751
+ segmentationId = segmentationId ?? rtDisplaySet.displaySetInstanceUID;
752
+ const { structureSet } = rtDisplaySet;
753
+
754
+ if (!structureSet) {
755
+ throw new Error(
756
+ 'To create the contours from RT displaySet, the displaySet should be loaded first. You can perform rtDisplaySet.load() before calling this method.'
757
+ );
758
+ }
759
+
760
+ const rtDisplaySetUID = rtDisplaySet.displaySetInstanceUID;
761
+ const referencedDisplaySet = this.servicesManager.services.displaySetService.getDisplaySetByUID(
762
+ rtDisplaySet.referencedDisplaySetInstanceUID
763
+ );
764
+
765
+ const referencedImageIdsWithGeometry = Array.from(structureSet.ReferencedSOPInstanceUIDsSet);
766
+
767
+ const referencedImageIds = referencedDisplaySet.imageIds;
768
+ // find the first image id that contains a referenced SOP instance UID
769
+ const firstSegmentedSliceImageId =
770
+ referencedImageIds?.find(imageId =>
771
+ referencedImageIdsWithGeometry.some(referencedId =>
772
+ imageId.includes(referencedId as string)
773
+ )
774
+ ) || null;
775
+
776
+ rtDisplaySet.firstSegmentedSliceImageId = firstSegmentedSliceImageId;
777
+
778
+ if (!structureSet.ROIContours?.length) {
779
+ throw new Error(
780
+ 'The structureSet does not contain any ROIContours. Please ensure the structureSet is loaded first.'
781
+ );
782
+ }
783
+
784
+ // Map ROI contours to RT Struct Data
785
+ const allRTStructData = mapROIContoursToRTStructData(structureSet, rtDisplaySetUID);
786
+
787
+ // Sort by segmentIndex for consistency
788
+ allRTStructData.sort((a, b) => a.segmentIndex - b.segmentIndex);
789
+
790
+ const geometryIds = allRTStructData.map(({ geometryId }) => geometryId);
791
+
792
+ // Initialize SegmentationPublicInput similar to SEG function
793
+ const segmentation: cstTypes.SegmentationPublicInput = {
794
+ segmentationId,
795
+ representation: {
796
+ type: CONTOUR,
797
+ data: {
798
+ geometryIds,
799
+ },
800
+ },
801
+ config: {
802
+ label: rtDisplaySet.SeriesDescription,
803
+ fallbackLabel: `S:${rtDisplaySet.SeriesNumber} ${rtDisplaySet.Modality}`,
804
+ },
805
+ };
806
+
807
+ const segments: { [segmentIndex: string]: cstTypes.Segment } = {};
808
+ let segmentsCachedStats = {};
809
+
810
+ // Create colorLUT array for RT structures
811
+ const colorLUT = [[0, 0, 0, 0]]; // First entry is transparent for index 0
812
+
813
+ // Process each segment similarly to the SEG function
814
+ for (let i = 0; i < allRTStructData.length; i++) {
815
+ const rtStructData = allRTStructData[i];
816
+
817
+ const { data, id, color, segmentIndex, geometryId, group } = rtStructData;
818
+
819
+ // Add the color to the colorLUT array
820
+ colorLUT.push(color);
821
+
822
+ try {
823
+ const geometry = await geometryLoader.createAndCacheGeometry(geometryId, {
824
+ geometryData: {
825
+ data,
826
+ id,
827
+ color,
828
+ frameOfReferenceUID: structureSet.frameOfReferenceUID,
829
+ segmentIndex,
830
+ },
831
+ type: csEnums.GeometryType.CONTOUR,
832
+ });
833
+
834
+ const contourSet = geometry.data as csTypes.IContourSet;
835
+ const centroid = contourSet.centroid;
836
+
837
+ segmentsCachedStats = {
838
+ center: { world: centroid },
839
+ modifiedTime: rtDisplaySet.SeriesDate, // Using SeriesDate as modifiedTime
840
+ };
841
+
842
+ segments[segmentIndex] = {
843
+ label: id,
844
+ segmentIndex,
845
+ cachedStats: segmentsCachedStats,
846
+ locked: false,
847
+ active: false,
848
+ group,
849
+ };
850
+
851
+ // Broadcast segment loading progress
852
+ const numInitialized = Object.keys(segmentsCachedStats).length;
853
+ const percentComplete = Math.round((numInitialized / allRTStructData.length) * 100);
854
+ this._broadcastEvent(EVENTS.SEGMENT_LOADING_COMPLETE, {
855
+ percentComplete,
856
+ numSegments: allRTStructData.length,
857
+ });
858
+ } catch (e) {
859
+ console.warn(`Error initializing contour for segment ${segmentIndex}:`, e);
860
+ continue; // Continue processing other segments even if one fails
861
+ }
862
+ }
863
+
864
+ // Create and register the colorLUT
865
+ const colorLUTIndex = addColorLUT(colorLUT);
866
+ this._segmentationIdToColorLUTIndexMap.set(segmentationId, colorLUTIndex);
867
+
868
+ // Assign processed segments to segmentation config
869
+ segmentation.config.segments = segments;
870
+
871
+ // Broadcast segmentation loading complete event
872
+ this._broadcastEvent(EVENTS.SEGMENTATION_LOADING_COMPLETE, {
873
+ segmentationId,
874
+ rtDisplaySet,
875
+ });
876
+
877
+ // Mark the RT display set as loaded
878
+ rtDisplaySet.isLoaded = true;
879
+ // Add or update the segmentation in the state
880
+ this.addOrUpdateSegmentation(segmentation);
881
+
882
+ return segmentationId;
883
+ }
884
+
885
+ /**
886
+ * Adds or updates a segmentation in the state
887
+ * @param segmentationId - The ID of the segmentation to add or update
888
+ * @param data - The data to add or update the segmentation with
889
+ *
890
+ * @remarks
891
+ * This method handles the addition or update of a segmentation in the state.
892
+ * If the segmentation already exists, it updates the existing segmentation.
893
+ * If the segmentation does not exist, it adds a new segmentation.
894
+ */
895
+ public addOrUpdateSegmentation(
896
+ data: cstTypes.SegmentationPublicInput | Partial<cstTypes.Segmentation>
897
+ ) {
898
+ const segmentationId = data.segmentationId;
899
+ const existingSegmentation = cstSegmentation.state.getSegmentation(segmentationId);
900
+
901
+ if (existingSegmentation) {
902
+ // Update the existing segmentation
903
+ this.updateSegmentationInSource(segmentationId, data as Partial<cstTypes.Segmentation>);
904
+ } else if (
905
+ 'representation' in data &&
906
+ (data as cstTypes.SegmentationPublicInput).representation
907
+ ) {
908
+ // Add a new segmentation
909
+ this.addSegmentationToSource(data as cstTypes.SegmentationPublicInput);
910
+ } else {
911
+ console.warn(
912
+ `addOrUpdateSegmentation: skipping add for ${segmentationId} — missing representation`
913
+ );
914
+ }
915
+ }
916
+
917
+ public setActiveSegmentation(viewportId: string, segmentationId: string): void {
918
+ cstSegmentation.activeSegmentation.setActiveSegmentation(viewportId, segmentationId);
919
+ }
920
+
921
+ /**
922
+ * Gets the active segmentation for a viewport
923
+ * @param viewportId - The ID of the viewport to get the active segmentation for
924
+ * @returns The active segmentation object, or null if no segmentation is active
925
+ *
926
+ * @remarks
927
+ * This method retrieves the currently active segmentation for the specified viewport.
928
+ * The active segmentation is the one that is currently selected for editing operations.
929
+ * Returns null if no segmentation is active in the viewport.
930
+ */
931
+ public getActiveSegmentation(viewportId: string): cstTypes.Segmentation | null {
932
+ return cstSegmentation.activeSegmentation.getActiveSegmentation(viewportId);
933
+ }
934
+
935
+ /**
936
+ * Gets the active segment from the active segmentation in a viewport
937
+ * @param viewportId - The ID of the viewport to get the active segment from
938
+ * @returns The active segment object, or undefined if no segment is active
939
+ *
940
+ * @remarks
941
+ * This method retrieves the currently active segment from the active segmentation
942
+ * in the specified viewport. The active segment is the one that is currently
943
+ * selected for editing operations. Returns undefined if no segment is active or
944
+ * if there is no active segmentation.
945
+ */
946
+ public getActiveSegment(viewportId: string): cstTypes.Segment | undefined {
947
+ const activeSegmentation = this.getActiveSegmentation(viewportId);
948
+
949
+ if (!activeSegmentation) {
950
+ return;
951
+ }
952
+
953
+ const { segments } = activeSegmentation;
954
+
955
+ let activeSegment;
956
+ for (const segment of Object.values(segments)) {
957
+ if (segment.active) {
958
+ activeSegment = segment;
959
+ break;
960
+ }
961
+ }
962
+
963
+ return activeSegment;
964
+ }
965
+
966
+ public hasCustomStyles(specifier: {
967
+ viewportId: string;
968
+ segmentationId: string;
969
+ type: csToolsEnums.SegmentationRepresentations;
970
+ }): boolean {
971
+ return cstSegmentation.config.style.hasCustomStyle(specifier);
972
+ }
973
+
974
+ public getStyle = (specifier: {
975
+ viewportId: string;
976
+ segmentationId: string;
977
+ type: csToolsEnums.SegmentationRepresentations;
978
+ segmentIndex?: number;
979
+ }) => {
980
+ const style = cstSegmentation.config.style.getStyle(specifier);
981
+
982
+ return style;
983
+ };
984
+
985
+ public setStyle = (
986
+ specifier: {
987
+ type: csToolsEnums.SegmentationRepresentations;
988
+ viewportId?: string;
989
+ segmentationId?: string;
990
+ segmentIndex?: number;
991
+ },
992
+ style: cstTypes.LabelmapStyle | cstTypes.ContourStyle | cstTypes.SurfaceStyle,
993
+ merge: boolean = true
994
+ ) => {
995
+ cstSegmentation.config.style.setStyle(specifier, style, merge);
996
+ this._broadcastEvent(EVENTS.SEGMENTATION_STYLE_MODIFIED, {
997
+ specifier,
998
+ style,
999
+ merge,
1000
+ });
1001
+ };
1002
+
1003
+ public resetToGlobalStyle = () => {
1004
+ cstSegmentation.config.style.resetToGlobalStyle();
1005
+ };
1006
+
1007
+ public getNextAvailableSegmentIndex(segmentationId: string): number {
1008
+ const csSegmentation = this.getCornerstoneSegmentation(segmentationId);
1009
+ // grab the next available segment index based on the object keys,
1010
+ // so basically get the highest segment index value + 1
1011
+
1012
+ const segmentKeys = Object.keys(csSegmentation.segments);
1013
+ return segmentKeys.length === 0 ? 1 : Math.max(...segmentKeys.map(Number)) + 1;
1014
+ }
1015
+
1016
+ /**
1017
+ * Adds a new segment to the specified segmentation.
1018
+ * @param segmentationId - The ID of the segmentation to add the segment to.
1019
+ * @param viewportId: The ID of the viewport to add the segment to, it is used to get the representation, if it is not
1020
+ * provided, the first available representation for the segmentationId will be used.
1021
+ * @param config - An object containing the configuration options for the new segment.
1022
+ * - segmentIndex: (optional) The index of the segment to add. If not provided, the next available index will be used.
1023
+ * - properties: (optional) An object containing the properties of the new segment.
1024
+ * - label: (optional) The label of the new segment. If not provided, a default label will be used.
1025
+ * - color: (optional) The color of the new segment in RGB format. If not provided, a default color will be used.
1026
+ * - visibility: (optional) Whether the new segment should be visible. If not provided, the segment will be visible by default.
1027
+ * - isLocked: (optional) Whether the new segment should be locked for editing. If not provided, the segment will not be locked by default.
1028
+ * - active: (optional) Whether the new segment should be the active segment to be edited. If not provided, the segment will not be active by default.
1029
+ */
1030
+ public addSegment(
1031
+ segmentationId: string,
1032
+ config: {
1033
+ segmentIndex?: number;
1034
+ label?: string;
1035
+ isLocked?: boolean;
1036
+ active?: boolean;
1037
+ color?: csTypes.Color; // Add color type
1038
+ visibility?: boolean; // Add visibility option
1039
+ cachedStats?: Record<string, unknown>;
1040
+ } = {}
1041
+ ): void {
1042
+ if (config?.segmentIndex === 0) {
1043
+ throw new Error(i18n.t('Segment') + ' index 0 is reserved for "no label"');
1044
+ }
1045
+
1046
+ const csSegmentation = this.getCornerstoneSegmentation(segmentationId);
1047
+
1048
+ let segmentIndex = config.segmentIndex;
1049
+ if (!segmentIndex) {
1050
+ segmentIndex = this.getNextAvailableSegmentIndex(segmentationId);
1051
+ }
1052
+
1053
+ // update the segmentation
1054
+ if (!config.label) {
1055
+ config.label = `${i18n.t('Segment')} ${segmentIndex}`;
1056
+ }
1057
+
1058
+ const currentSegments = csSegmentation.segments;
1059
+
1060
+ cstSegmentation.updateSegmentations([
1061
+ {
1062
+ segmentationId,
1063
+ payload: {
1064
+ segments: {
1065
+ ...currentSegments,
1066
+ [segmentIndex]: {
1067
+ ...currentSegments[segmentIndex],
1068
+ segmentIndex,
1069
+ cachedStats: {},
1070
+ locked: false,
1071
+ ...config,
1072
+ },
1073
+ },
1074
+ },
1075
+ },
1076
+ ]);
1077
+
1078
+ this.setActiveSegment(segmentationId, segmentIndex);
1079
+
1080
+ // Apply additional configurations
1081
+ if (config.isLocked !== undefined) {
1082
+ this._setSegmentLockedStatus(segmentationId, segmentIndex, config.isLocked);
1083
+ }
1084
+
1085
+ // Get all viewports that have this segmentation
1086
+ const viewportIds = this.getViewportIdsWithSegmentation(segmentationId);
1087
+
1088
+ viewportIds.forEach(viewportId => {
1089
+ // Set color if provided
1090
+ if (config.color !== undefined) {
1091
+ this.setSegmentColor(viewportId, segmentationId, segmentIndex, config.color);
1092
+ }
1093
+
1094
+ // Set visibility if provided
1095
+ if (config.visibility !== undefined) {
1096
+ this.setSegmentVisibility(viewportId, segmentationId, segmentIndex, config.visibility);
1097
+ }
1098
+ });
1099
+ }
1100
+
1101
+ /**
1102
+ * Creates a memo that records the current state of a segment (segmentationId/segmentIndex)
1103
+ * so that undo can restore it via addSegment and redo can call removeSegment again
1104
+ * without recording history.
1105
+ *
1106
+ * @param segmentationId - The ID of the segmentation.
1107
+ * @param segmentIndex - The index of the segment (must still exist when called).
1108
+ * @param _options - Reserved (e.g. deleting) for future use.
1109
+ * @returns A Memo with restoreMemo(undo): undo => addSegment, redo => removeSegment (skipRecordingHistory).
1110
+ */
1111
+ public createSegmentIndexMemo(
1112
+ segmentationId: string,
1113
+ segmentIndex: number,
1114
+ _options?: { deleting?: boolean }
1115
+ ): csTypes.Memo | null {
1116
+ const csSegmentation = this.getCornerstoneSegmentation(segmentationId);
1117
+ const segment = csSegmentation?.segments?.[segmentIndex];
1118
+ if (!segment) {
1119
+ return null;
1120
+ }
1121
+
1122
+ let color: csTypes.Color | undefined;
1123
+ let visibility: boolean | undefined;
1124
+ const viewportIds = this.getViewportIdsWithSegmentation(segmentationId);
1125
+ if (viewportIds.length > 0) {
1126
+ const firstViewportId = viewportIds[0];
1127
+ const representations = this.getSegmentationRepresentations(firstViewportId, {
1128
+ segmentationId,
1129
+ });
1130
+ const repType = representations[0]?.type ?? LABELMAP;
1131
+ color = this.getSegmentColor(firstViewportId, segmentationId, segmentIndex);
1132
+ visibility = cstSegmentation.config.visibility.getSegmentIndexVisibility(
1133
+ firstViewportId,
1134
+ { segmentationId, type: repType },
1135
+ segmentIndex
1136
+ );
1137
+ }
1138
+
1139
+ const segmentState = {
1140
+ segmentIndex,
1141
+ label: segment.label,
1142
+ isLocked: segment.locked,
1143
+ active: segment.active,
1144
+ color,
1145
+ visibility,
1146
+ };
1147
+
1148
+ const service = this;
1149
+ const memo: csTypes.Memo = {
1150
+ id: csUtils.uuidv4(),
1151
+ operationType: 'segmentIndex',
1152
+ restoreMemo(undo?: boolean) {
1153
+ if (undo === true) {
1154
+ service.addSegment(segmentationId, segmentState);
1155
+ } else {
1156
+ // Redo: remove the segment via cornerstone without recording history
1157
+ cstSegmentation.removeSegment(segmentationId, segmentIndex, { recordHistory: false });
1158
+ }
1159
+ },
1160
+ };
1161
+ return memo;
1162
+ }
1163
+
1164
+ /**
1165
+ * Removes a segment from a segmentation and updates the active segment index if necessary.
1166
+ *
1167
+ * @param segmentationId - The ID of the segmentation containing the segment to remove.
1168
+ * @param segmentIndex - The index of the segment to remove.
1169
+ * @param options - Optional. skipRecordingHistory: if true, do not push undo memo (used when redoing).
1170
+ *
1171
+ * @remarks
1172
+ * This method performs the following actions:
1173
+ * 1. Clears the segment value in the Cornerstone segmentation.
1174
+ * 2. Updates all related segmentation representations to remove the segment.
1175
+ * 3. If the removed segment was the active segment, it updates the active segment index.
1176
+ *
1177
+ */
1178
+ public removeSegment(
1179
+ segmentationId: string,
1180
+ segmentIndex: number,
1181
+ options?: { skipRecordingHistory?: boolean }
1182
+ ): void {
1183
+ let memo;
1184
+ if (!options?.skipRecordingHistory) {
1185
+ memo = this.createSegmentIndexMemo(segmentationId, segmentIndex, { deleting: true });
1186
+ DefaultHistoryMemo.startGroupRecording();
1187
+ cstSegmentation.removeSegment(segmentationId, segmentIndex, { recordHistory: true });
1188
+ DefaultHistoryMemo.push(memo);
1189
+ DefaultHistoryMemo.endGroupRecording();
1190
+ } else {
1191
+ cstSegmentation.removeSegment(segmentationId, segmentIndex, { recordHistory: false });
1192
+ }
1193
+ }
1194
+
1195
+ public setSegmentVisibility(
1196
+ viewportId: string,
1197
+ segmentationId: string,
1198
+ segmentIndex: number,
1199
+ isVisible: boolean,
1200
+ type?: csToolsEnums.SegmentationRepresentations
1201
+ ): void {
1202
+ this._setSegmentVisibility(viewportId, segmentationId, segmentIndex, isVisible, type);
1203
+ }
1204
+
1205
+ /**
1206
+ * Sets the locked status of a segment in a segmentation.
1207
+ *
1208
+ * @param segmentationId - The ID of the segmentation containing the segment.
1209
+ * @param segmentIndex - The index of the segment to set the locked status for.
1210
+ * @param isLocked - The new locked status of the segment.
1211
+ *
1212
+ * @remarks
1213
+ * This method updates the locked status of a specific segment within a segmentation.
1214
+ * A locked segment cannot be modified or edited.
1215
+ */
1216
+ public setSegmentLocked(segmentationId: string, segmentIndex: number, isLocked: boolean): void {
1217
+ this._setSegmentLockedStatus(segmentationId, segmentIndex, isLocked);
1218
+ }
1219
+
1220
+ /**
1221
+ * Toggles the locked state of a segment in a segmentation.
1222
+ * @param segmentationId - The ID of the segmentation.
1223
+ * @param segmentIndex - The index of the segment to toggle.
1224
+ */
1225
+ public toggleSegmentLocked(segmentationId: string, segmentIndex: number): void {
1226
+ const isLocked = cstSegmentation.segmentLocking.isSegmentIndexLocked(
1227
+ segmentationId,
1228
+ segmentIndex
1229
+ );
1230
+ this._setSegmentLockedStatus(segmentationId, segmentIndex, !isLocked);
1231
+ }
1232
+
1233
+ public toggleSegmentVisibility(
1234
+ viewportId: string,
1235
+ segmentationId: string,
1236
+ segmentIndex: number,
1237
+ type: csToolsEnums.SegmentationRepresentations
1238
+ ): void {
1239
+ const isVisible = cstSegmentation.config.visibility.getSegmentIndexVisibility(
1240
+ viewportId,
1241
+ {
1242
+ segmentationId,
1243
+ type,
1244
+ },
1245
+ segmentIndex
1246
+ );
1247
+ this._setSegmentVisibility(viewportId, segmentationId, segmentIndex, !isVisible, type);
1248
+ }
1249
+
1250
+ /**
1251
+ * Sets the color of a specific segment in a segmentation.
1252
+ *
1253
+ * @param viewportId - The ID of the viewport containing the segmentation
1254
+ * @param segmentationId - The ID of the segmentation containing the segment
1255
+ * @param segmentIndex - The index of the segment to set the color for
1256
+ * @param color - The new color to apply to the segment as an array of RGBA values
1257
+ *
1258
+ * @remarks
1259
+ * This method updates the color of a specific segment within a segmentation.
1260
+ * The color parameter should be an array of 4 numbers representing RGBA values.
1261
+ */
1262
+ public setSegmentColor(
1263
+ viewportId: string,
1264
+ segmentationId: string,
1265
+ segmentIndex: number,
1266
+ color: csTypes.Color
1267
+ ): void {
1268
+ const segmentationRepresentations = this.getSegmentationRepresentations(viewportId, {
1269
+ segmentationId,
1270
+ });
1271
+ const { colorLUTIndex } = segmentationRepresentations[0];
1272
+ this._segmentationIdToColorLUTIndexMap.set(segmentationId, colorLUTIndex);
1273
+
1274
+ cstSegmentation.config.color.setSegmentIndexColor(
1275
+ viewportId,
1276
+ segmentationId,
1277
+ segmentIndex,
1278
+ color
1279
+ );
1280
+ }
1281
+
1282
+ /**
1283
+ * Gets the current color of a specific segment in a segmentation.
1284
+ *
1285
+ * @param viewportId - The ID of the viewport containing the segmentation
1286
+ * @param segmentationId - The ID of the segmentation containing the segment
1287
+ * @param segmentIndex - The index of the segment to get the color for
1288
+ * @returns An array of 4 numbers representing the RGBA color values of the segment
1289
+ *
1290
+ * @remarks
1291
+ * This method retrieves the current color of a specific segment within a segmentation.
1292
+ * The returned color is an array of 4 numbers representing RGBA values.
1293
+ */
1294
+ public getSegmentColor(viewportId: string, segmentationId: string, segmentIndex: number) {
1295
+ return cstSegmentation.config.color.getSegmentIndexColor(
1296
+ viewportId,
1297
+ segmentationId,
1298
+ segmentIndex
1299
+ );
1300
+ }
1301
+
1302
+ /**
1303
+ * Gets the labelmap volume for a segmentation
1304
+ * @param segmentationId - The ID of the segmentation to get the labelmap volume for
1305
+ * @returns The labelmap volume for the segmentation, or null if not found
1306
+ *
1307
+ * @remarks
1308
+ * This method retrieves the labelmap volume data for a specific segmentation.
1309
+ * The labelmap volume contains the actual segmentation data in the form of a 3D volume.
1310
+ * Returns null if the segmentation does not have valid labelmap volume data.
1311
+ */
1312
+ public getLabelmapVolume(segmentationId: string) {
1313
+ const csSegmentation = cstSegmentation.state.getSegmentation(segmentationId);
1314
+ const labelmapData = csSegmentation.representationData[
1315
+ LABELMAP
1316
+ ] as cstTypes.LabelmapToolOperationDataVolume;
1317
+
1318
+ if (!labelmapData || !labelmapData.volumeId) {
1319
+ return null;
1320
+ }
1321
+
1322
+ const { volumeId } = labelmapData;
1323
+ const labelmapVolume = cache.getVolume(volumeId);
1324
+
1325
+ return labelmapVolume;
1326
+ }
1327
+
1328
+ /**
1329
+ * Sets the label for a specific segment in a segmentation
1330
+ * @param segmentationId - The ID of the segmentation containing the segment
1331
+ * @param segmentIndex - The index of the segment to set the label for
1332
+ * @param label - The new label to apply to the segment
1333
+ *
1334
+ * @remarks
1335
+ * This method updates the text label of a specific segment within a segmentation.
1336
+ * The label is used to identify and describe the segment in the UI.
1337
+ */
1338
+ public setSegmentLabel(segmentationId: string, segmentIndex: number, label: string) {
1339
+ this._setSegmentLabel(segmentationId, segmentIndex, label);
1340
+ }
1341
+
1342
+ /**
1343
+ * Sets the active segment for a segmentation
1344
+ * @param segmentationId - The ID of the segmentation containing the segment
1345
+ * @param segmentIndex - The index of the segment to set as active
1346
+ *
1347
+ * @remarks
1348
+ * This method updates which segment is considered "active" within a segmentation.
1349
+ * The active segment is typically highlighted and available for editing operations.
1350
+ */
1351
+ public setActiveSegment(segmentationId: string, segmentIndex: number): void {
1352
+ this._setActiveSegment(segmentationId, segmentIndex);
1353
+ }
1354
+
1355
+ /**
1356
+ * Controls whether inactive segmentations should be rendered in a viewport
1357
+ * @param viewportId - The ID of the viewport to update
1358
+ * @param renderInactive - Whether inactive segmentations should be rendered
1359
+ *
1360
+ * @remarks
1361
+ * This method configures if segmentations that are not currently active
1362
+ * should still be visible in the specified viewport. This can be useful
1363
+ * for comparing or viewing multiple segmentations simultaneously.
1364
+ */
1365
+ public setRenderInactiveSegmentations(viewportId: string, renderInactive: boolean): void {
1366
+ cstSegmentation.config.style.setRenderInactiveSegmentations(viewportId, renderInactive);
1367
+ }
1368
+
1369
+ /**
1370
+ * Gets whether inactive segmentations are being rendered for a viewport
1371
+ * @param viewportId - The ID of the viewport to check
1372
+ * @returns boolean indicating if inactive segmentations are rendered
1373
+ *
1374
+ * @remarks
1375
+ * This method retrieves the current rendering state for inactive segmentations
1376
+ * in the specified viewport. Returns true if inactive segmentations are visible.
1377
+ */
1378
+ public getRenderInactiveSegmentations(viewportId: string): boolean {
1379
+ return cstSegmentation.config.style.getRenderInactiveSegmentations(viewportId);
1380
+ }
1381
+ /**
1382
+ * Sets statistics for a group of segmentations
1383
+ * @param segmentationIds - Array of segmentation IDs that form the group
1384
+ * @param stats - Statistics object containing metrics for the segmentation group
1385
+ *
1386
+ * @remarks
1387
+ * This method stores statistical data for a group of related segmentations.
1388
+ * The stats are stored using a composite key created from the sorted and joined
1389
+ */
1390
+ public setSegmentationGroupStats(segmentationIds: string[], stats: any) {
1391
+ const groupId = this.getGroupId(segmentationIds);
1392
+ this._segmentationGroupStatsMap.set(groupId, stats);
1393
+ }
1394
+
1395
+ /**
1396
+ * Gets statistics for a group of segmentations
1397
+ * @param segmentationIds - Array of segmentation IDs that form the group
1398
+ * @returns The stored statistics object for the segmentation group if found, undefined otherwise
1399
+ */
1400
+ public getSegmentationGroupStats(segmentationIds: string[]) {
1401
+ const groupId = this.getGroupId(segmentationIds);
1402
+ return this._segmentationGroupStatsMap.get(groupId);
1403
+ }
1404
+
1405
+ private getGroupId(segmentationIds: string[]) {
1406
+ return segmentationIds.sort().join(',');
1407
+ }
1408
+
1409
+ /**
1410
+ * Toggles the visibility of a segmentation in the state, and broadcasts the event.
1411
+ * Note: this method does not update the segmentation state in the source. It only
1412
+ * updates the state, and there should be separate listeners for that.
1413
+ * @param ids segmentation ids
1414
+ */
1415
+ public toggleSegmentationRepresentationVisibility = (
1416
+ viewportId: string,
1417
+ {
1418
+ segmentationId,
1419
+ type,
1420
+ }: { segmentationId: string; type: csToolsEnums.SegmentationRepresentations }
1421
+ ): void => {
1422
+ this._toggleSegmentationRepresentationVisibility(viewportId, segmentationId, type);
1423
+ };
1424
+
1425
+ public getViewportIdsWithSegmentation = (segmentationId: string): string[] => {
1426
+ const viewportIds = cstSegmentation.state.getViewportIdsWithSegmentation(segmentationId);
1427
+ return viewportIds;
1428
+ };
1429
+
1430
+ /**
1431
+ * Clears segmentation representations from the viewport.
1432
+ * Unlike removeRepresentationsFromViewport, this doesn't update
1433
+ * removed display set and representation maps.
1434
+ * We track removed segmentations manually to avoid re-adding them
1435
+ * when the display set is added again.
1436
+ * @param viewportId - The viewport ID to clear segmentation representations from.
1437
+ */
1438
+ public clearSegmentationRepresentations(viewportId: string): void {
1439
+ this.removeRepresentationsFromViewport(viewportId);
1440
+ }
1441
+
1442
+ /**
1443
+ * Completely removes a segmentation from the state
1444
+ * @param segmentationId - The ID of the segmentation to remove.
1445
+ */
1446
+ public remove(segmentationId: string): void {
1447
+ cstSegmentation.state.removeSegmentation(segmentationId);
1448
+ }
1449
+
1450
+ public removeAllSegmentations(): void {
1451
+ cstSegmentation.state.removeAllSegmentations();
1452
+ }
1453
+
1454
+ /**
1455
+ * Removes segmentation representations from the viewport.
1456
+ * @param viewportId - The viewport id to remove the segmentation representations from.
1457
+ * @param specifier - The specifier to remove the segmentation representations.
1458
+ *
1459
+ * @remarks
1460
+ * If no specifier is provided, all segmentation representations for the viewport are removed.
1461
+ * If a segmentationId specifier is provided, only the segmentation representation with the specified segmentationId and type are removed.
1462
+ * If a type specifier is provided, only the segmentation representation with the specified type are removed.
1463
+ * If both a segmentationId and type specifier are provided, only the segmentation representation with the specified segmentationId and type are removed.
1464
+ */
1465
+ public removeRepresentationsFromViewport(
1466
+ viewportId: string,
1467
+ specifier: {
1468
+ segmentationId?: string;
1469
+ type?: csToolsEnums.SegmentationRepresentations;
1470
+ } = {}
1471
+ ): void {
1472
+ cstSegmentation.removeSegmentationRepresentations(viewportId, specifier);
1473
+ }
1474
+
1475
+ /**
1476
+ * Jumps to the next slice that contains the specified segment in the viewport.
1477
+ * For labelmaps, it jumps to the segment center. For contours, it cycles through
1478
+ * all slices that contain contour data for the segment.
1479
+ *
1480
+ * @param segmentationId - The ID of the segmentation
1481
+ * @param segmentIndex - The index of the segment to jump to
1482
+ * @param viewportId - Optional viewport ID. If not provided, applies to all viewports with this segmentation
1483
+ * @param highlightAlpha - Alpha value for highlighting (0-1)
1484
+ * @param highlightSegment - Whether to highlight the segment after jumping
1485
+ * @param animationLength - Length of highlight animation in milliseconds
1486
+ * @param highlightHideOthers - Whether to hide other segments during highlight
1487
+ * @param animationFunctionType - The easing function to use for animation
1488
+ */
1489
+ public jumpToSegmentNext(
1490
+ segmentationId: string,
1491
+ segmentIndex: number,
1492
+ forViewportId?: string,
1493
+ direction = 1,
1494
+ highlightAlpha = 0.9,
1495
+ highlightSegment = true,
1496
+ animationLength = 750,
1497
+ highlightHideOthers = false,
1498
+ animationFunctionType: EasingFunctionEnum = EasingFunctionEnum.EASE_IN_OUT
1499
+ ): void {
1500
+ const viewportIds = forViewportId
1501
+ ? [forViewportId]
1502
+ : this.getViewportIdsWithSegmentation(segmentationId);
1503
+
1504
+ viewportIds.forEach(viewportId => {
1505
+ const representations = this.getSegmentationRepresentations(viewportId, {
1506
+ segmentationId,
1507
+ });
1508
+
1509
+ if (!representations || representations.length === 0) {
1510
+ return;
1511
+ }
1512
+
1513
+ const representation = representations[0];
1514
+ const { type } = representation;
1515
+
1516
+ // For contours, check if we have a segment center.
1517
+ const center =
1518
+ type === CONTOUR ? this._getSegmentCenter(segmentationId, segmentIndex) : undefined;
1519
+ const canUseSegmentCenter = type !== CONTOUR || !!center;
1520
+ if (canUseSegmentCenter) {
1521
+ this.jumpToSegmentCenter(
1522
+ segmentationId,
1523
+ segmentIndex,
1524
+ viewportId,
1525
+ highlightAlpha,
1526
+ highlightSegment,
1527
+ animationLength,
1528
+ highlightHideOthers,
1529
+ animationFunctionType,
1530
+ center
1531
+ );
1532
+ return;
1533
+ }
1534
+
1535
+ const { viewport } = getEnabledElementByViewportId(viewportId);
1536
+ if (!viewport) {
1537
+ return;
1538
+ }
1539
+
1540
+ const viewRefs = this._getContourViewReferences(segmentationId, viewport, segmentIndex);
1541
+ if (!viewRefs) {
1542
+ return;
1543
+ }
1544
+
1545
+ // Get the current slice index
1546
+ const currentSliceIndex = viewport.getCurrentImageIdIndex();
1547
+ let nearestSliceIndex = null;
1548
+ let loopSliceIndex = null;
1549
+
1550
+ for (const [sliceIndex] of viewRefs.entries()) {
1551
+ // Track loop index for wraparound (smallest for forward, largest for backward)
1552
+ if (direction > 0) {
1553
+ if (loopSliceIndex === null || sliceIndex < loopSliceIndex) {
1554
+ loopSliceIndex = sliceIndex;
1555
+ }
1556
+ } else {
1557
+ if (loopSliceIndex === null || sliceIndex > loopSliceIndex) {
1558
+ loopSliceIndex = sliceIndex;
1559
+ }
1560
+ }
1561
+
1562
+ if (direction > 0) {
1563
+ // Forward direction: find nearest slice after current
1564
+ if (sliceIndex <= currentSliceIndex) {
1565
+ continue;
1566
+ }
1567
+ if (nearestSliceIndex === null || sliceIndex < nearestSliceIndex) {
1568
+ nearestSliceIndex = sliceIndex;
1569
+ }
1570
+ } else {
1571
+ // Backward direction: find nearest slice before current
1572
+ if (sliceIndex >= currentSliceIndex) {
1573
+ continue;
1574
+ }
1575
+ if (nearestSliceIndex === null || sliceIndex > nearestSliceIndex) {
1576
+ nearestSliceIndex = sliceIndex;
1577
+ }
1578
+ }
1579
+ }
1580
+
1581
+ // Wraparound: if no slice found in direction, use loop index
1582
+ nearestSliceIndex = nearestSliceIndex ?? loopSliceIndex;
1583
+ if (nearestSliceIndex === null) {
1584
+ return;
1585
+ }
1586
+ const viewRef = viewRefs.get(nearestSliceIndex);
1587
+ viewport.setViewReference(viewRef);
1588
+ viewport.render();
1589
+ });
1590
+ }
1591
+
1592
+ /**
1593
+ * Jumps the viewport to the center of hte given segment.
1594
+ * Only works for labelmaps, and may result in not showing any contours.
1595
+ */
1596
+ public jumpToSegmentCenter(
1597
+ segmentationId: string,
1598
+ segmentIndex: number,
1599
+ viewportId?: string,
1600
+ highlightAlpha = 0.9,
1601
+ highlightSegment = true,
1602
+ animationLength = 750,
1603
+ highlightHideOthers = false,
1604
+ animationFunctionType: EasingFunctionEnum = EasingFunctionEnum.EASE_IN_OUT,
1605
+ center?: { image?: csTypes.Point3; world: csTypes.Point3 }
1606
+ ): void {
1607
+ const resolvedCenter = center ?? this._getSegmentCenter(segmentationId, segmentIndex);
1608
+ if (!resolvedCenter) {
1609
+ console.warn('No center found for segmentation', segmentationId, segmentIndex);
1610
+ return;
1611
+ }
1612
+
1613
+ const { world } = resolvedCenter as { world: csTypes.Point3 };
1614
+
1615
+ // need to find which viewports are displaying the segmentation
1616
+ const viewportIds = viewportId
1617
+ ? [viewportId]
1618
+ : this.getViewportIdsWithSegmentation(segmentationId);
1619
+
1620
+ viewportIds.forEach(viewportId => {
1621
+ const { viewport } = getEnabledElementByViewportId(viewportId);
1622
+ if (!viewport) {
1623
+ return;
1624
+ }
1625
+
1626
+ // Recenter via the backend twin: legacy jumpToWorld, or native setViewReference
1627
+ // (a native PlanarViewport has no jumpToWorld). Skip the highlight when the
1628
+ // recenter did not happen, matching the previous guarded behavior.
1629
+ const didJump = this._segBackend(viewport).jumpToSegmentCenter(viewport, world);
1630
+
1631
+ didJump &&
1632
+ highlightSegment &&
1633
+ this.highlightSegment(
1634
+ segmentationId,
1635
+ segmentIndex,
1636
+ viewportId,
1637
+ highlightAlpha,
1638
+ animationLength,
1639
+ highlightHideOthers,
1640
+ animationFunctionType
1641
+ );
1642
+ });
1643
+ }
1644
+
1645
+ public highlightSegment(
1646
+ segmentationId: string,
1647
+ segmentIndex: number,
1648
+ viewportId?: string,
1649
+ alpha = 0.9,
1650
+ animationLength = 750,
1651
+ hideOthers = true,
1652
+ animationFunctionType: EasingFunctionEnum = EasingFunctionEnum.EASE_IN_OUT
1653
+ ): void {
1654
+ const csSegmentation = this.getCornerstoneSegmentation(segmentationId);
1655
+
1656
+ this._endSegmentHighlightsOtherThan(segmentationId, segmentIndex);
1657
+
1658
+ const viewportIds = viewportId
1659
+ ? [viewportId]
1660
+ : this.getViewportIdsWithSegmentation(segmentationId);
1661
+
1662
+ viewportIds.forEach(viewportId => {
1663
+ const segmentationRepresentation = this.getSegmentationRepresentations(viewportId, {
1664
+ segmentationId,
1665
+ });
1666
+
1667
+ const representation = segmentationRepresentation[0];
1668
+ const { type } = representation;
1669
+ const segments = csSegmentation.segments;
1670
+
1671
+ // Viewports showing the same representation type share the segment's style, and
1672
+ // so one animation. Selecting the segment again while it animates continues it.
1673
+ const key = segmentHighlightKey(segmentationId, segmentIndex, type);
1674
+ if (this._segmentHighlights.get(key)?.state === 'highlighting') {
1675
+ return;
1676
+ }
1677
+ const highlight: SegmentHighlight = {
1678
+ segmentationId,
1679
+ segmentIndex,
1680
+ type,
1681
+ state: 'highlighting',
1682
+ };
1683
+
1684
+ const highlightFn =
1685
+ type === LABELMAP ? this._highlightLabelmap.bind(this) : this._highlightContour.bind(this);
1686
+
1687
+ const adjustedAlpha = type === LABELMAP ? alpha : 1 - alpha;
1688
+
1689
+ highlightFn(
1690
+ segmentIndex,
1691
+ adjustedAlpha,
1692
+ hideOthers,
1693
+ segments,
1694
+ viewportId,
1695
+ animationLength,
1696
+ representation,
1697
+ animationFunctionType,
1698
+ highlight
1699
+ );
1700
+ // Registered only once the animation is set up, so a highlight that throws
1701
+ // does not leave the segment looking as if it were still animating.
1702
+ this._segmentHighlights.set(key, highlight);
1703
+ });
1704
+ }
1705
+
1706
+ /**
1707
+ * Deselects every highlighted segment but the given one. A segment still
1708
+ * animating has its temporary style reset now, not on its loop's next frame,
1709
+ * so a highlight that starts right after reads the segment's real style.
1710
+ */
1711
+ private _endSegmentHighlightsOtherThan(segmentationId: string, segmentIndex: number): void {
1712
+ this._segmentHighlights.forEach((highlight, key) => {
1713
+ if (highlight.segmentationId === segmentationId && highlight.segmentIndex === segmentIndex) {
1714
+ return;
1715
+ }
1716
+ this._segmentHighlights.delete(key);
1717
+ if (highlight.state === 'highlighting') {
1718
+ this._resetSegmentHighlightStyle(highlight);
1719
+ }
1720
+ });
1721
+ }
1722
+
1723
+ private _isCurrentSegmentHighlight(highlight: SegmentHighlight): boolean {
1724
+ const { segmentationId, segmentIndex, type } = highlight;
1725
+ return (
1726
+ this._segmentHighlights.get(segmentHighlightKey(segmentationId, segmentIndex, type)) ===
1727
+ highlight
1728
+ );
1729
+ }
1730
+
1731
+ /**
1732
+ * Wraps a highlight's animation frame so it runs only while the highlight is
1733
+ * current. A frame that throws ends the highlight, so the segment can be
1734
+ * highlighted again, and resets the temporary style an earlier frame may have
1735
+ * applied, since nothing else will once the highlight is forgotten.
1736
+ */
1737
+ private _segmentHighlightFrame(
1738
+ highlight: SegmentHighlight,
1739
+ frame: FrameRequestCallback
1740
+ ): FrameRequestCallback {
1741
+ return (time: number) => {
1742
+ if (!this._isCurrentSegmentHighlight(highlight)) {
1743
+ return;
1744
+ }
1745
+ try {
1746
+ frame(time);
1747
+ } catch (error) {
1748
+ const { segmentationId, segmentIndex, type } = highlight;
1749
+ this._segmentHighlights.delete(segmentHighlightKey(segmentationId, segmentIndex, type));
1750
+ if (this.getCornerstoneSegmentation(segmentationId)) {
1751
+ try {
1752
+ this._resetSegmentHighlightStyle(highlight);
1753
+ } catch {
1754
+ // The frame's error is the one to report.
1755
+ }
1756
+ }
1757
+ throw error;
1758
+ }
1759
+ };
1760
+ }
1761
+
1762
+ private _completeSegmentHighlight(highlight: SegmentHighlight): void {
1763
+ highlight.state = 'selected';
1764
+ this._resetSegmentHighlightStyle(highlight);
1765
+ }
1766
+
1767
+ private _resetSegmentHighlightStyle({ segmentationId, segmentIndex, type }: SegmentHighlight) {
1768
+ cstSegmentation.config.style.setStyle({ segmentationId, segmentIndex, type }, {}, false);
1769
+ }
1770
+
1771
+ private getAndValidateViewport(viewportId: string) {
1772
+ const csViewport =
1773
+ this.servicesManager.services.cornerstoneViewportService.getCornerstoneViewport(viewportId);
1774
+ if (!csViewport) {
1775
+ console.warn(`Viewport with id ${viewportId} not found.`);
1776
+ return null;
1777
+ }
1778
+ return csViewport;
1779
+ }
1780
+
1781
+ /**
1782
+ * Sets the visibility of a segmentation representation.
1783
+ *
1784
+ * @param viewportId - The ID of the viewport.
1785
+ * @param segmentationId - The ID of the segmentation.
1786
+ * @param isVisible - The new visibility state.
1787
+ */
1788
+ private _setSegmentationRepresentationVisibility(
1789
+ viewportId: string,
1790
+ segmentationId: string,
1791
+ type: csToolsEnums.SegmentationRepresentations,
1792
+ isVisible: boolean
1793
+ ): void {
1794
+ const representations = this.getSegmentationRepresentations(viewportId, {
1795
+ segmentationId,
1796
+ type,
1797
+ });
1798
+ const representation = representations[0];
1799
+
1800
+ if (!representation) {
1801
+ console.debug(
1802
+ 'No segmentation representation found for the given viewportId and segmentationId'
1803
+ );
1804
+ return;
1805
+ }
1806
+
1807
+ cstSegmentation.config.visibility.setSegmentationRepresentationVisibility(
1808
+ viewportId,
1809
+ {
1810
+ segmentationId,
1811
+ type,
1812
+ },
1813
+ isVisible
1814
+ );
1815
+ }
1816
+
1817
+ // Labelmap-add classification (determineViewportAndSegmentationType +
1818
+ // handleViewportConversion + the stack/volume case handlers) now lives in the
1819
+ // segmentation backend twins (backends/{Legacy,Next}SegmentationBackend), routed
1820
+ // per viewport via _segBackend(). The legacy twin reaches the viewport-recreation
1821
+ // and data-volume-conversion helpers below through ISegmentationServiceInternals.
1822
+
1823
+ private async _addSegmentationRepresentation(
1824
+ viewportId: string,
1825
+ segmentationId: string,
1826
+ representationType: csToolsEnums.SegmentationRepresentations,
1827
+ colorLUTIndex: number,
1828
+ isConverted: boolean,
1829
+ config?: {
1830
+ blendMode?: csEnums.BlendModes;
1831
+ useSliceRendering?: boolean;
1832
+ }
1833
+ ): Promise<void> {
1834
+ const representation = {
1835
+ type: representationType,
1836
+ segmentationId,
1837
+ config: { colorLUTOrIndex: colorLUTIndex, ...config },
1838
+ };
1839
+
1840
+ const addRepresentation = () =>
1841
+ cstSegmentation.addSegmentationRepresentations(viewportId, [representation]);
1842
+
1843
+ if (isConverted) {
1844
+ const { viewportGridService } = this.servicesManager.services;
1845
+ await new Promise<void>(resolve => {
1846
+ const { unsubscribe } = viewportGridService.subscribe(
1847
+ viewportGridService.EVENTS.GRID_STATE_CHANGED,
1848
+ () => {
1849
+ addRepresentation();
1850
+ unsubscribe();
1851
+ resolve();
1852
+ }
1853
+ );
1854
+ });
1855
+ } else {
1856
+ addRepresentation();
1857
+ }
1858
+ }
1859
+ public async handleVolumeViewport(
1860
+ viewport: csTypes.IVolumeViewport,
1861
+ segmentation: SegmentationData,
1862
+ isVolumeSegmentation: boolean
1863
+ ): Promise<void> {
1864
+ if (isVolumeSegmentation) {
1865
+ return; // Volume Labelmap on Volume Viewport is natively supported
1866
+ }
1867
+
1868
+ const frameOfReferenceUID = viewport.getFrameOfReferenceUID();
1869
+ const imageIds = getLabelmapImageIds(segmentation.segmentationId);
1870
+ const segImage = cache.getImage(imageIds[0]);
1871
+
1872
+ if (segImage?.FrameOfReferenceUID === frameOfReferenceUID) {
1873
+ await convertStackToVolumeLabelmap(segmentation);
1874
+ }
1875
+ }
1876
+
1877
+ public async convertStackToVolumeViewport(viewport: csTypes.IViewport): Promise<boolean> {
1878
+ const { viewportGridService, cornerstoneViewportService } = this.servicesManager.services;
1879
+ const state = viewportGridService.getState();
1880
+ const gridViewport = state.viewports.get(viewport.id);
1881
+
1882
+ const prevViewPresentation = viewport.getViewPresentation();
1883
+ const prevViewReference = viewport.getViewReference();
1884
+ const stackViewport = cornerstoneViewportService.getCornerstoneViewport(viewport.id);
1885
+ const { element } = stackViewport;
1886
+
1887
+ const volumeViewportNewVolumeHandler = () => {
1888
+ const volumeViewport = cornerstoneViewportService.getCornerstoneViewport(viewport.id);
1889
+ volumeViewport.setViewPresentation(prevViewPresentation);
1890
+ volumeViewport.setViewReference(prevViewReference);
1891
+ volumeViewport.render();
1892
+
1893
+ element.removeEventListener(
1894
+ csEnums.Events.VOLUME_VIEWPORT_NEW_VOLUME,
1895
+ volumeViewportNewVolumeHandler
1896
+ );
1897
+ };
1898
+
1899
+ element.addEventListener(
1900
+ csEnums.Events.VOLUME_VIEWPORT_NEW_VOLUME,
1901
+ volumeViewportNewVolumeHandler
1902
+ );
1903
+
1904
+ viewportGridService.setDisplaySetsForViewport({
1905
+ viewportId: viewport.id,
1906
+ displaySetInstanceUIDs: gridViewport.displaySetInstanceUIDs,
1907
+ viewportOptions: {
1908
+ ...gridViewport.viewportOptions,
1909
+ viewportType: ViewportType.ORTHOGRAPHIC,
1910
+ },
1911
+ });
1912
+
1913
+ return true;
1914
+ }
1915
+
1916
+ public async attemptStackToVolumeConversion(
1917
+ viewport: csTypes.IStackViewport,
1918
+ segmentation: SegmentationData,
1919
+ viewportId: string,
1920
+ segmentationId: string
1921
+ ): Promise<boolean> {
1922
+ const imageIds = getLabelmapImageIds(segmentation.segmentationId);
1923
+ const frameOfReferenceUID = viewport.getFrameOfReferenceUID();
1924
+ const segImage = cache.getImage(imageIds[0]);
1925
+
1926
+ if (
1927
+ segImage?.FrameOfReferenceUID &&
1928
+ frameOfReferenceUID &&
1929
+ segImage.FrameOfReferenceUID === frameOfReferenceUID
1930
+ ) {
1931
+ const isConverted = await this.convertStackToVolumeViewport(viewport);
1932
+ triggerSegmentationRepresentationModified(viewportId, segmentationId, LABELMAP);
1933
+
1934
+ return isConverted;
1935
+ }
1936
+
1937
+ // Frame-of-reference mismatch (or missing): no conversion happened. Return an
1938
+ // explicit boolean so the Promise<boolean> contract holds for callers.
1939
+ return false;
1940
+ }
1941
+
1942
+ private addSegmentationToSource(segmentationPublicInput: cstTypes.SegmentationPublicInput) {
1943
+ cstSegmentation.addSegmentations([segmentationPublicInput]);
1944
+ }
1945
+
1946
+ private updateSegmentationInSource(
1947
+ segmentationId: string,
1948
+ payload: Partial<cstTypes.Segmentation>
1949
+ ) {
1950
+ cstSegmentation.updateSegmentations([{ segmentationId, payload }]);
1951
+ }
1952
+
1953
+ private _toOHIFSegmentationRepresentation(
1954
+ viewportId: string,
1955
+ csRepresentation: cstTypes.SegmentationRepresentation
1956
+ ): SegmentationRepresentation {
1957
+ const { segmentationId, type, active, visible } = csRepresentation;
1958
+ const { colorLUTIndex } = csRepresentation;
1959
+
1960
+ const segmentsRepresentations: { [segmentIndex: number]: SegmentRepresentation } = {};
1961
+
1962
+ const segmentation = cstSegmentation.state.getSegmentation(segmentationId);
1963
+
1964
+ if (!segmentation) {
1965
+ throw new Error(`Segmentation with ID ${segmentationId} not found.`);
1966
+ }
1967
+
1968
+ const segmentIds = Object.keys(segmentation.segments);
1969
+
1970
+ for (const segmentId of segmentIds) {
1971
+ const segmentIndex = parseInt(segmentId, 10);
1972
+
1973
+ const color = cstSegmentation.config.color.getSegmentIndexColor(
1974
+ viewportId,
1975
+ segmentationId,
1976
+ segmentIndex
1977
+ );
1978
+
1979
+ const isVisible = cstSegmentation.config.visibility.getSegmentIndexVisibility(
1980
+ viewportId,
1981
+ {
1982
+ segmentationId,
1983
+ type,
1984
+ },
1985
+ segmentIndex
1986
+ );
1987
+
1988
+ segmentsRepresentations[segmentIndex] = {
1989
+ color,
1990
+ segmentIndex,
1991
+ opacity: color[3],
1992
+ visible: isVisible,
1993
+ };
1994
+ }
1995
+
1996
+ const styles = cstSegmentation.config.style.getStyle({
1997
+ viewportId,
1998
+ segmentationId,
1999
+ type,
2000
+ });
2001
+
2002
+ const id = `${segmentationId}-${type}-${viewportId}`;
2003
+
2004
+ return {
2005
+ id: id,
2006
+ segmentationId,
2007
+ label: segmentation.label,
2008
+ fallbackLabel: segmentation.fallbackLabel,
2009
+ active,
2010
+ type,
2011
+ visible,
2012
+ segments: segmentsRepresentations,
2013
+ styles,
2014
+ viewportId,
2015
+ colorLUTIndex,
2016
+ config: {},
2017
+ };
2018
+ }
2019
+
2020
+ private _initSegmentationService() {
2021
+ eventTarget.addEventListener(
2022
+ csToolsEnums.Events.SEGMENTATION_MODIFIED,
2023
+ this._onSegmentationModifiedFromSource
2024
+ );
2025
+
2026
+ eventTarget.addEventListener(
2027
+ csToolsEnums.Events.SEGMENTATION_REMOVED,
2028
+ this._onSegmentationRemovedFromSource
2029
+ );
2030
+
2031
+ eventTarget.addEventListener(
2032
+ csToolsEnums.Events.SEGMENTATION_DATA_MODIFIED,
2033
+ this._onSegmentationDataModifiedFromSource
2034
+ );
2035
+
2036
+ eventTarget.addEventListener(
2037
+ csToolsEnums.Events.SEGMENTATION_REPRESENTATION_MODIFIED,
2038
+ this._onSegmentationRepresentationModifiedFromSource
2039
+ );
2040
+
2041
+ eventTarget.addEventListener(
2042
+ csToolsEnums.Events.SEGMENTATION_REPRESENTATION_ADDED,
2043
+ this._onSegmentationRepresentationModifiedFromSource
2044
+ );
2045
+
2046
+ eventTarget.addEventListener(
2047
+ csToolsEnums.Events.SEGMENTATION_REPRESENTATION_REMOVED,
2048
+ this._onSegmentationRepresentationRemovedFromSource
2049
+ );
2050
+
2051
+ eventTarget.addEventListener(
2052
+ csToolsEnums.Events.SEGMENTATION_ADDED,
2053
+ this._onSegmentationAddedFromSource
2054
+ );
2055
+
2056
+ eventTarget.addEventListener(
2057
+ csToolsEnums.Events.ANNOTATION_CUT_MERGE_PROCESS_COMPLETED,
2058
+ this._onAnnotationCutMergeProcessCompletedFromSource
2059
+ );
2060
+ }
2061
+
2062
+ private getCornerstoneSegmentation(segmentationId: string) {
2063
+ return cstSegmentation.state.getSegmentation(segmentationId);
2064
+ }
2065
+
2066
+ private _highlightLabelmap(
2067
+ segmentIndex: number,
2068
+ alpha: number,
2069
+ hideOthers: boolean,
2070
+ segments: cstTypes.Segment[],
2071
+ viewportId: string,
2072
+ animationLength: number,
2073
+ representation: cstTypes.SegmentationRepresentation,
2074
+ animationFunctionType: EasingFunctionEnum,
2075
+ highlight: SegmentHighlight
2076
+ ) {
2077
+ const { segmentationId } = representation;
2078
+ const newSegmentSpecificConfig = {
2079
+ fillAlpha: alpha,
2080
+ };
2081
+
2082
+ if (hideOthers) {
2083
+ throw new Error('hideOthers is not working right now');
2084
+ }
2085
+
2086
+ const { fillAlpha } = this.getStyle({
2087
+ viewportId,
2088
+ segmentationId,
2089
+ type: LABELMAP,
2090
+ segmentIndex,
2091
+ }) as cstTypes.LabelmapStyle;
2092
+
2093
+ let startTime: number = null;
2094
+ const animation = this._segmentHighlightFrame(highlight, (timestamp: number) => {
2095
+ if (startTime === null) {
2096
+ startTime = timestamp;
2097
+ }
2098
+
2099
+ const elapsed = timestamp - startTime;
2100
+ const progress = Math.min(elapsed / animationLength, 1);
2101
+
2102
+ const easingFunction = EasingFunctionMap.get(animationFunctionType);
2103
+
2104
+ cstSegmentation.config.style.setStyle(
2105
+ {
2106
+ segmentationId,
2107
+ segmentIndex,
2108
+ type: LABELMAP,
2109
+ },
2110
+ {
2111
+ fillAlpha: easingFunction(progress, fillAlpha),
2112
+ }
2113
+ );
2114
+
2115
+ if (progress < 1) {
2116
+ requestAnimationFrame(animation);
2117
+ } else {
2118
+ this._completeSegmentHighlight(highlight);
2119
+ }
2120
+ });
2121
+
2122
+ requestAnimationFrame(animation);
2123
+ }
2124
+
2125
+ private _highlightContour(
2126
+ segmentIndex: number,
2127
+ alpha: number,
2128
+ hideOthers: boolean,
2129
+ segments: cstTypes.Segment[],
2130
+ viewportId: string,
2131
+ animationLength: number,
2132
+ representation: cstTypes.SegmentationRepresentation,
2133
+ animationFunctionType: EasingFunctionEnum,
2134
+ highlight: SegmentHighlight
2135
+ ) {
2136
+ const { segmentationId } = representation;
2137
+ const startTime = performance.now();
2138
+
2139
+ const prevStyle = cstSegmentation.config.style.getStyle({
2140
+ type: CONTOUR,
2141
+ }) as cstTypes.ContourStyle;
2142
+
2143
+ const prevOutlineWidth = prevStyle.outlineWidth;
2144
+
2145
+ const animate = this._segmentHighlightFrame(highlight, (currentTime: number) => {
2146
+ const progress = (currentTime - startTime) / animationLength;
2147
+ if (progress >= 1) {
2148
+ this._completeSegmentHighlight(highlight);
2149
+ return;
2150
+ }
2151
+
2152
+ const OUTLINE_ANIMATION_SCALE_FACTOR = 5;
2153
+ const easingFunction = EasingFunctionMap.get(animationFunctionType);
2154
+
2155
+ cstSegmentation.config.style.setStyle(
2156
+ {
2157
+ segmentationId,
2158
+ segmentIndex,
2159
+ type: CONTOUR,
2160
+ },
2161
+ {
2162
+ outlineWidth: easingFunction(progress, prevOutlineWidth, OUTLINE_ANIMATION_SCALE_FACTOR),
2163
+ }
2164
+ );
2165
+
2166
+ requestAnimationFrame(animate);
2167
+ });
2168
+
2169
+ requestAnimationFrame(animate);
2170
+ }
2171
+
2172
+ private _toggleSegmentationRepresentationVisibility = (
2173
+ viewportId: string,
2174
+ segmentationId: string,
2175
+ type: csToolsEnums.SegmentationRepresentations
2176
+ ): void => {
2177
+ const segmentsHidden = cstSegmentation.config.visibility.getHiddenSegmentIndices(viewportId, {
2178
+ segmentationId,
2179
+ type,
2180
+ });
2181
+
2182
+ const currentVisibility = segmentsHidden.size === 0;
2183
+ this._setSegmentationRepresentationVisibility(
2184
+ viewportId,
2185
+ segmentationId,
2186
+ type,
2187
+ !currentVisibility
2188
+ );
2189
+ };
2190
+
2191
+ private _setActiveSegment(segmentationId: string, segmentIndex: number) {
2192
+ cstSegmentation.segmentIndex.setActiveSegmentIndex(segmentationId, segmentIndex);
2193
+ }
2194
+
2195
+ private _getVolumeIdForDisplaySet(displaySet) {
2196
+ const volumeLoaderSchema = displaySet.volumeLoaderSchema ?? VOLUME_LOADER_SCHEME;
2197
+
2198
+ return `${volumeLoaderSchema}:${displaySet.displaySetInstanceUID}`;
2199
+ }
2200
+
2201
+ private _getSegmentCenter(
2202
+ segmentationId: string,
2203
+ segmentIndex: number
2204
+ ): { image?: csTypes.Point3; world: csTypes.Point3 } | undefined {
2205
+ const segmentation = this.getSegmentation(segmentationId);
2206
+
2207
+ if (!segmentation) {
2208
+ return;
2209
+ }
2210
+
2211
+ const { segments } = segmentation;
2212
+
2213
+ const { cachedStats } = segments[segmentIndex];
2214
+
2215
+ if (cachedStats?.center) {
2216
+ const { center } = cachedStats;
2217
+
2218
+ return center as { image: csTypes.Point3; world: csTypes.Point3 };
2219
+ }
2220
+
2221
+ if (cachedStats?.namedStats?.center) {
2222
+ return {
2223
+ world: cachedStats.namedStats.center.value,
2224
+ };
2225
+ }
2226
+ }
2227
+
2228
+ private _setSegmentLockedStatus(segmentationId: string, segmentIndex: number, isLocked: boolean) {
2229
+ cstSegmentation.segmentLocking.setSegmentIndexLocked(segmentationId, segmentIndex, isLocked);
2230
+ }
2231
+
2232
+ private _setSegmentVisibility(
2233
+ viewportId: string,
2234
+ segmentationId: string,
2235
+ segmentIndex: number,
2236
+ isVisible: boolean,
2237
+ type?: csToolsEnums.SegmentationRepresentations
2238
+ ) {
2239
+ cstSegmentation.config.visibility.setSegmentIndexVisibility(
2240
+ viewportId,
2241
+ {
2242
+ segmentationId,
2243
+ type,
2244
+ },
2245
+ segmentIndex,
2246
+ isVisible
2247
+ );
2248
+ }
2249
+
2250
+ private _setSegmentLabel(segmentationId: string, segmentIndex: number, segmentLabel: string) {
2251
+ const segmentation = this.getCornerstoneSegmentation(segmentationId);
2252
+ const { segments } = segmentation;
2253
+
2254
+ segments[segmentIndex].label = segmentLabel;
2255
+
2256
+ cstSegmentation.updateSegmentations([
2257
+ {
2258
+ segmentationId,
2259
+ payload: {
2260
+ segments,
2261
+ },
2262
+ },
2263
+ ]);
2264
+ }
2265
+
2266
+ private _onSegmentationDataModifiedFromSource = evt => {
2267
+ const { segmentationId } = evt.detail;
2268
+ this._broadcastEvent(this.EVENTS.SEGMENTATION_DATA_MODIFIED, {
2269
+ segmentationId,
2270
+ });
2271
+ };
2272
+
2273
+ private _onSegmentationRepresentationModifiedFromSource = evt => {
2274
+ const { segmentationId, viewportId } = evt.detail;
2275
+ this._broadcastEvent(this.EVENTS.SEGMENTATION_REPRESENTATION_MODIFIED, {
2276
+ segmentationId,
2277
+ viewportId,
2278
+ });
2279
+ };
2280
+
2281
+ private _onSegmentationRepresentationRemovedFromSource = evt => {
2282
+ const { segmentationId, viewportId } = evt.detail;
2283
+ this._broadcastEvent(this.EVENTS.SEGMENTATION_REPRESENTATION_REMOVED, {
2284
+ segmentationId,
2285
+ viewportId,
2286
+ });
2287
+ };
2288
+
2289
+ private _onSegmentationModifiedFromSource = (
2290
+ evt: cstTypes.EventTypes.SegmentationModifiedEventType
2291
+ ) => {
2292
+ const { segmentationId } = evt.detail;
2293
+
2294
+ this._broadcastEvent(this.EVENTS.SEGMENTATION_MODIFIED, {
2295
+ segmentationId,
2296
+ });
2297
+ };
2298
+
2299
+ private _onSegmentationAddedFromSource = (
2300
+ evt: cstTypes.EventTypes.SegmentationAddedEventType
2301
+ ) => {
2302
+ const { segmentationId } = evt.detail;
2303
+
2304
+ this._broadcastEvent(this.EVENTS.SEGMENTATION_ADDED, {
2305
+ segmentationId,
2306
+ });
2307
+ };
2308
+
2309
+ private _onSegmentationRemovedFromSource = (
2310
+ evt: cstTypes.EventTypes.SegmentationRemovedEventType
2311
+ ) => {
2312
+ const { segmentationId } = evt.detail;
2313
+
2314
+ this._segmentHighlights.forEach((highlight, key) => {
2315
+ if (highlight.segmentationId === segmentationId) {
2316
+ this._segmentHighlights.delete(key);
2317
+ }
2318
+ });
2319
+
2320
+ this._broadcastEvent(this.EVENTS.SEGMENTATION_REMOVED, {
2321
+ segmentationId,
2322
+ });
2323
+ };
2324
+
2325
+ private _onAnnotationCutMergeProcessCompletedFromSource = evt => {
2326
+ const { segmentationId } = evt.detail;
2327
+ this._broadcastEvent(this.EVENTS.SEGMENTATION_ANNOTATION_CUT_MERGE_PROCESS_COMPLETED, {
2328
+ segmentationId,
2329
+ });
2330
+ };
2331
+
2332
+ /**
2333
+ * Gets slice indices for contour segmentations by checking view references from annotation metadata
2334
+ * @private
2335
+ */
2336
+ protected _getContourViewReferences(
2337
+ segmentationId: string,
2338
+ viewport: csTypes.IViewport,
2339
+ segmentIndex?: number
2340
+ ): Map<number, ViewReference> | undefined {
2341
+ const segmentation = cstSegmentation.state.getSegmentation(segmentationId);
2342
+ const contourData = segmentation.representationData[CONTOUR];
2343
+
2344
+ if (!contourData || !contourData.annotationUIDsMap) {
2345
+ return;
2346
+ }
2347
+
2348
+ const viewReferences = new Map<number, ViewReference>();
2349
+ // Iterate through the annotationUIDsMap
2350
+ contourData.annotationUIDsMap.forEach((annotationUIDs, currentSegmentIndex) => {
2351
+ // Filter by segment index if specified
2352
+ if (segmentIndex !== undefined && currentSegmentIndex !== segmentIndex) {
2353
+ return;
2354
+ }
2355
+ // Process each annotation UID
2356
+ annotationUIDs.forEach(annotationUID => {
2357
+ const annotation = cstAnnotation.state.getAnnotation(annotationUID);
2358
+
2359
+ if (!annotation?.metadata) {
2360
+ return;
2361
+ }
2362
+ const { metadata } = annotation;
2363
+ // Check if the viewport can view this annotation's view reference with navigation
2364
+ const isViewable = viewport.isReferenceViewable(metadata, {
2365
+ withNavigation: true,
2366
+ });
2367
+
2368
+ if (!isViewable) {
2369
+ return;
2370
+ }
2371
+
2372
+ const { sliceIndex } = metadata;
2373
+ if (sliceIndex === undefined) {
2374
+ console.warn("Can't find slice index:", metadata);
2375
+ return;
2376
+ }
2377
+
2378
+ viewReferences.set(sliceIndex, metadata);
2379
+ });
2380
+ });
2381
+
2382
+ if (viewReferences.size === 0) {
2383
+ return;
2384
+ }
2385
+ return viewReferences;
2386
+ }
2387
+ }
2388
+
2389
+ export default SegmentationService;
2390
+ export { EVENTS, VALUE_TYPES };