From c7f9af8025b689056febb876bc1fe1a75e4691b2 Mon Sep 17 00:00:00 2001 From: SantaSpeen Date: Sun, 22 Nov 2026 01:14:03 +0300 Subject: [PATCH] Integrate DICOM series and Metal volume viewer --- README.md | 10 +- Sources/EzDent/DICOM.swift | 197 ++++++++++++++++++++++++++ Sources/EzDent/DICOMViewer.swift | 145 +++++++++++++++++++ Sources/EzDent/DICOMVolume.swift | 109 ++++++++++++++ Sources/EzDent/PatientLibrary.swift | 33 +++++ Sources/EzDent/PatientWorkspace.swift | 29 +++- Sources/EzDent/VolumeProjection.swift | 179 +++++++++++++++++++++++ 7 files changed, 696 insertions(+), 6 deletions(-) create mode 100644 Sources/EzDent/DICOM.swift create mode 100644 Sources/EzDent/DICOMViewer.swift create mode 100644 Sources/EzDent/DICOMVolume.swift create mode 100644 Sources/EzDent/VolumeProjection.swift diff --git a/README.md b/README.md index 8dccf81..336ff17 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ open dist/EzDent.app В просмотрщике можно менять масштаб, поворот, яркость и контраст. Настройки просмотра не изменяют оригинал. Кнопка «Экспорт оригинала…» сохраняет исходный файл. -Из справки Windows-версии взяты сценарии поиска и редактирования карточек, импорта и просмотра снимков и настройки яркости и контраста. DICOM, 3D, отчёты и захват с оборудования пока не реализованы. +Из справки Windows-версии взяты сценарии поиска и редактирования карточек, импорта и просмотра снимков и настройки яркости и контраста. Отчёты и захват с оборудования пока не реализованы. В настройках приложения (`⌘,`) можно сохранить хост и порт ezServer и проверить TCP-подключение к этому адресу. Клиент пока не выполняет авторизацию и запросы к API. @@ -35,3 +35,11 @@ open dist/EzDent.app - В шаблоне `VTServerConfig.ini` указаны File Manager (55001), Patch Manager (55011) и EzWebServer (43112). Порт 55005 указан дополнительно для поиска. Клиент macOS по умолчанию предлагает 43112 и позволяет изменить порт. - Шаблон `VTDBConfig.ini` указывает на PostgreSQL. В Windows-бинарнике есть ссылки на HTTP, `/api/v1` и авторизацию. Эти артефакты сами по себе не определяют, каким способом конкретная инсталляция отдаёт карточки и снимки. Для интеграции нужно подтвердить контракт API на ezServer. - Установщик изучался статически без запуска. Windows-бинарники, ресурсы и настройки из дистрибутива не входят в приложение macOS. + +## DICOM и 3D + +- Нажмите «Добавить снимки…» и выберите файл DICOM для 2D-просмотра. Для 3D выберите одновременно все файлы **одной** серии однослойных срезов. EzDent сортирует их по геометрии, независимо от имён и порядка выбора. При импорте оригиналы копируются в локальную библиотеку. +- Для серии доступны три плоскости с учётом физического размера вокселей. Ползунки «Уровень» и «Окно» меняют отображение. +- Режим «3D» открывается в той же карточке. Перетаскивайте изображение, чтобы вращать объём. Доступны пороговая поверхность и проекция максимальной интенсивности (MIP), масштаб и сброс ракурса. +- Читаются монохромные DICOM Part 10 без сжатия с 8- или 16-битными пикселями, Explicit или Implicit VR Little Endian. Многофреймовый файл можно листать в 2D. Для 3D нужны отдельные срезы с одинаковой ориентацией, размером и равномерным шагом. JPEG/JPEG 2000/RLE, цвет и Enhanced CT с геометрией по кадрам пока не поддерживаются. Для 3D текстура уменьшается до 256 вокселей по длинной стороне. Совместимость с клиническими сериями ezServer ещё не проверялась. +- В установщике Ez3D-i 5.5.12.3 найдены отдельные модули DICOM, MPR и VolumeViz. Приложение macOS реализует эти сценарии средствами SwiftUI и Metal. Геометрия серии строится по [DICOM PS3.3 C.7.6.2](https://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.7.6.2.html), декодирование использует [DICOM PS3.5, раздел A](https://dicom.nema.org/medical/dicom/current/output/chtml/part05/chapter_A.html). diff --git a/Sources/EzDent/DICOM.swift b/Sources/EzDent/DICOM.swift new file mode 100644 index 0000000..971720f --- /dev/null +++ b/Sources/EzDent/DICOM.swift @@ -0,0 +1,197 @@ +import CoreGraphics +import Foundation +import simd + +struct DICOMImage { + struct Geometry { + let origin: SIMD3 + let row: SIMD3 + let column: SIMD3 + let spacing: SIMD2 + } + + let width: Int + let height: Int + let frames: Int + let pixels: [Float] + let monochrome1: Bool + let window: SIMD2? + let series: String? + let geometry: Geometry? + + static func recognizes(_ url: URL) -> Bool { + guard let file = try? FileHandle(forReadingFrom: url) else { return false } + defer { try? file.close() } + try? file.seek(toOffset: 128) + return (try? file.read(upToCount: 4)) == Data("DICM".utf8) + } + + init(url: URL) throws { + let data = try Data(contentsOf: url, options: .mappedIfSafe) + guard data.count >= 132, data[128..<132].elementsEqual("DICM".utf8) else { + throw DICOMError.invalid + } + var reader = DICOMReader(data) + var syntax = "" + while reader.group == 2 { + let element = try reader.element(explicit: true) + if element.tag == 0x0002_0010 { syntax = reader.string(element.range) } + } + guard syntax == "1.2.840.10008.1.2" || syntax == "1.2.840.10008.1.2.1" else { + throw DICOMError.transferSyntax + } + + let explicit = syntax.hasSuffix(".1") + var fields: [UInt32: Range] = [:] + while reader.group != nil { + let element = try reader.element(explicit: explicit) + if element.tag == 0x7FE0_0010 { + fields[element.tag] = element.range + break + } + fields[element.tag] = element.range + } + func number(_ tag: UInt32) -> Int? { + guard let range = fields[tag], range.count == 2 else { return nil } + return Int(reader.word(range.lowerBound)) + } + func string(_ tag: UInt32) -> String? { + fields[tag].map(reader.string) + } + func decimals(_ tag: UInt32, count: Int) -> [Double]? { + guard let value = string(tag) else { return nil } + let values = value.split(separator: "\\").compactMap { + Double($0.trimmingCharacters(in: .whitespaces)) + } + return values.count == count && values.allSatisfy(\.isFinite) ? values : nil + } + func decimal(_ tag: UInt32) -> Float? { + guard let first = string(tag)?.split(separator: "\\").first, + let value = Float(first.trimmingCharacters(in: .whitespaces)), value.isFinite else { return nil } + return value + } + + let frameCount = string(0x0028_0008).flatMap(Int.init) ?? 1 + guard let width = number(0x0028_0011), let height = number(0x0028_0010), + width > 0, height > 0, (1...4096).contains(frameCount), + width * height <= 32_000_000 / frameCount, + number(0x0028_0002) == 1, + let photometric = string(0x0028_0004), ["MONOCHROME1", "MONOCHROME2"].contains(photometric), + let bits = number(0x0028_0100), bits == 8 || bits == 16, + let stored = number(0x0028_0101), (1...bits).contains(stored), + number(0x0028_0102) == stored - 1, + let representation = number(0x0028_0103), representation == 0 || representation == 1, + let pixelRange = fields[0x7FE0_0010] else { throw DICOMError.unsupported } + let sampleCount = width * height * frameCount + let bytes = bits / 8 + let length = sampleCount * bytes + guard pixelRange.count == length || (length % 2 == 1 && pixelRange.count == length + 1) else { + throw DICOMError.invalid + } + + let mask = (1 << stored) - 1 + let signBit = 1 << (stored - 1) + let slope = decimal(0x0028_1053) ?? 1 + let intercept = decimal(0x0028_1052) ?? 0 + guard abs(slope) <= 1_000_000, abs(intercept) <= 1_000_000_000 else { throw DICOMError.invalid } + self.width = width + self.height = height + frames = frameCount + monochrome1 = photometric == "MONOCHROME1" + series = string(0x0020_000E) + if let center = decimal(0x0028_1050), let windowWidth = decimal(0x0028_1051), windowWidth >= 1 { + window = SIMD2(center, windowWidth) + } else { + window = nil + } + if let position = decimals(0x0020_0032, count: 3), + let axes = decimals(0x0020_0037, count: 6), + let spacing = decimals(0x0028_0030, count: 2), spacing.allSatisfy({ $0 > 0 }) { + geometry = Geometry(origin: SIMD3(position[0], position[1], position[2]), + row: SIMD3(axes[0], axes[1], axes[2]), + column: SIMD3(axes[3], axes[4], axes[5]), + spacing: SIMD2(spacing[1], spacing[0])) + } else { + geometry = nil + } + + pixels = data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in + (0.. CGImage? { + let bytes = pixels.map { value -> UInt8 in + let normalized = span <= 1 ? (value > center - 0.5 ? Float(1) : 0) + : min(1, max(0, (value - (center - 0.5)) / (span - 1) + 0.5)) + return UInt8(((invert ? 1 - normalized : normalized) * 255).rounded()) + } + guard let provider = CGDataProvider(data: Data(bytes) as CFData) else { return nil } + return CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 8, + bytesPerRow: width, space: CGColorSpaceCreateDeviceGray(), + bitmapInfo: [], provider: provider, decode: nil, shouldInterpolate: true, + intent: .defaultIntent) + } +} + +enum DICOMError: LocalizedError { + case invalid, transferSyntax, unsupported, geometry + var errorDescription: String? { + switch self { + case .invalid: return "Файл DICOM повреждён или имеет неподдерживаемую структуру." + case .transferSyntax: return "Поддерживается DICOM Little Endian без сжатия." + case .unsupported: return "Поддерживаются монохромные DICOM с пикселями 8 или 16 бит в пределах лимита памяти." + case .geometry: return "Для 3D выберите все срезы одной серии с одинаковой геометрией и равномерным шагом." + } + } +} + +private struct DICOMReader { + let data: Data + var cursor = 132 + var group: UInt16? { cursor <= data.count - 8 ? word(cursor) : nil } + private static let longVR: Set = ["OB", "OD", "OF", "OL", "OV", "OW", "SQ", "SV", "UC", "UN", "UR", "UT", "UV"] + + init(_ data: Data) { self.data = data } + + func word(_ offset: Int) -> UInt16 { + UInt16(data[offset]) | UInt16(data[offset + 1]) << 8 + } + + func string(_ range: Range) -> String { + String(decoding: data[range], as: UTF8.self) + .trimmingCharacters(in: .whitespacesAndNewlines.union(CharacterSet(charactersIn: "\0"))) + } + + mutating func element(explicit: Bool, depth: Int = 0) throws -> (tag: UInt32, range: Range) { + guard let group, depth < 32 else { throw DICOMError.invalid } + let tag = UInt32(group) << 16 | UInt32(word(cursor + 2)) + let long = group == 0xfffe || !explicit + || Self.longVR.contains(String(decoding: data[(cursor + 4)..<(cursor + 6)], as: UTF8.self)) + let header = long && group != 0xfffe && explicit ? 12 : 8 + guard cursor <= data.count - header else { throw DICOMError.invalid } + let lengthOffset = cursor + header - (long ? 4 : 2) + let length = long ? Int(word(lengthOffset)) | Int(word(lengthOffset + 2)) << 16 : Int(word(lengthOffset)) + cursor += header + if length == Int(UInt32.max) { + guard tag != 0x7FE0_0010 else { throw DICOMError.transferSyntax } + let delimiter: UInt32 = tag == 0xFFFE_E000 ? 0xFFFE_E00D : 0xFFFE_E0DD + while true { + let child = try element(explicit: explicit, depth: depth + 1) + if child.tag == delimiter { break } + } + return (tag, cursor..(0.4, -0.3) + @State private var dragOrigin: SIMD2? + @State private var zoom = 1.0 + + var body: some View { + Group { + if let volume { + viewer(volume) + } else if let error { + Text(error).padding() + } else { + ProgressView("Загрузка DICOM…") + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + .task { + do { + let urls = self.urls + let loaded = try await Task.detached(priority: .userInitiated) { + try DICOMVolume(urls: urls) + }.value + guard !Task.isCancelled else { return } + resetWindow(loaded) + index = Double(loaded.size.z / 2) + volume = loaded + } catch { + self.error = error.localizedDescription + } + } + } + + private func viewer(_ volume: DICOMVolume) -> some View { + VStack(spacing: 0) { + HStack { + if volume.spacing != nil { + Picker("Режим", selection: $show3D) { + Text("Срезы").tag(false) + Text("3D").tag(true) + } + .pickerStyle(.segmented) + .frame(width: 145) + .onChange(of: show3D) { is3D in + if is3D && renderer == nil { renderer = VolumeRenderer(volume: volume) } + } + if !show3D { + Picker("Плоскость", selection: $plane) { + ForEach(DICOMVolume.Plane.allCases) { Text($0.rawValue).tag($0) } + } + .onChange(of: plane) { index = Double(volume.count($0) / 2) } + } else { + Picker("Проекция", selection: $surface) { + Text("Поверхность").tag(true) + Text("Максимум (MIP)").tag(false) + } + Button("Сбросить ракурс") { + zoom = 1 + rotation = SIMD2(0.4, -0.3) + } + } + } + Spacer() + Text("DICOM • \(volume.size.x) × \(volume.size.y) × \(volume.size.z)") + .font(.caption) + .foregroundStyle(.secondary) + } + .padding(10) + + ZStack { + Color.black + if show3D { + if let renderer { + VolumeProjection(renderer: renderer, rotation: rotation, zoom: Float(zoom), + window: SIMD2(Float(center), Float(width)), surface: surface) + .overlay { + Color.clear.contentShape(Rectangle()) + .gesture(DragGesture() + .onChanged { + let start = dragOrigin ?? rotation + dragOrigin = start + rotation = start + SIMD2(Float($0.translation.width), Float($0.translation.height)) * 0.01 + } + .onEnded { _ in dragOrigin = nil }) + } + } else { + Text("3D недоступно на этом Mac").foregroundStyle(.white) + } + } else if let (image, aspect) = volume.image(plane, index: min(Int(index), volume.count(plane) - 1), + center: Float(center), span: Float(width)) { + Image(decorative: image, scale: 1) + .resizable() + .aspectRatio(aspect, contentMode: .fit) + .accessibilityLabel("Срез DICOM") + .padding(12) + } + } + + VStack(spacing: 6) { + if show3D { + Slider(value: $zoom, in: 0.5...3) { Text("Масштаб 3D") } + } else if volume.count(plane) > 1 { + Slider(value: $index, in: 0...Double(volume.count(plane) - 1), step: 1) { + Text("Срез \(min(Int(index) + 1, volume.count(plane))) из \(volume.count(plane))") + } + } + HStack { + Slider(value: $center, in: centerRange(volume)) { Text(show3D && surface ? "Порог" : "Уровень") } + if !show3D || !surface { + Slider(value: $width, in: 1...windowLimit(volume)) { Text("Окно") } + } + Button("Сбросить окно") { resetWindow(volume) } + } + } + .padding(10) + } + } + + private func centerRange(_ volume: DICOMVolume) -> ClosedRange { + let preset = volume.window?.x ?? volume.minimum + return Double(min(volume.minimum, preset))...Double(max(volume.minimum + 1, volume.maximum, preset)) + } + + private func resetWindow(_ volume: DICOMVolume) { + let span = max(2, Double(volume.maximum - volume.minimum)) + center = volume.window.map { Double($0.x) } ?? (Double(volume.minimum) + span / 2) + width = volume.window.map { Double($0.y) } ?? span + } + + private func windowLimit(_ volume: DICOMVolume) -> Double { + max(2, Double(volume.maximum - volume.minimum), Double(volume.window?.y ?? 1)) + } +} diff --git a/Sources/EzDent/DICOMVolume.swift b/Sources/EzDent/DICOMVolume.swift new file mode 100644 index 0000000..7ea3178 --- /dev/null +++ b/Sources/EzDent/DICOMVolume.swift @@ -0,0 +1,109 @@ +import CoreGraphics +import Foundation +import simd + +struct DICOMVolume { + enum Plane: String, CaseIterable, Identifiable { + case slices = "Срезы серии" + case coronal = "Поперёк рядов" + case sagittal = "Поперёк столбцов" + + var id: Self { self } + } + + let size: SIMD3 + let spacing: SIMD3? + let pixels: [Float] + let window: SIMD2? + let inverted: Bool + let minimum: Float + let maximum: Float + + init(urls: [URL]) throws { + guard !urls.isEmpty, urls.count <= 4096 else { throw DICOMError.geometry } + let first = try DICOMImage(url: urls[0]) + let planeSize = first.width * first.height + guard planeSize <= 64_000_000 / urls.count else { throw DICOMError.unsupported } + size = SIMD3(first.width, first.height, urls.count == 1 ? first.frames : urls.count) + window = first.window + inverted = first.monochrome1 + if urls.count == 1 { + spacing = nil + pixels = first.pixels + } else { + guard let series = first.series, !series.isEmpty, let basis = first.geometry, + abs(simd_length(basis.row) - 1) < 0.001, + abs(simd_length(basis.column) - 1) < 0.001, + abs(simd_dot(basis.row, basis.column)) < 0.001 else { throw DICOMError.geometry } + let normal = simd_normalize(simd_cross(basis.row, basis.column)) + func position(_ image: DICOMImage) throws -> Double { + guard image.frames == 1, image.series == series, image.width == first.width, + image.height == first.height, image.monochrome1 == first.monochrome1, + let geometry = image.geometry, + simd_distance(geometry.row, basis.row) < 0.001, + simd_distance(geometry.column, basis.column) < 0.001, + simd_distance(geometry.spacing, basis.spacing) < 0.001 else { throw DICOMError.geometry } + let offset = geometry.origin - basis.origin + let depth = simd_dot(offset, normal) + guard depth.isFinite, simd_length(offset - depth * normal) < 0.1 else { throw DICOMError.geometry } + return depth + } + + var slices = [(depth: try position(first), pixels: first.pixels)] + for url in urls.dropFirst() { + let image = try DICOMImage(url: url) + slices.append((try position(image), image.pixels)) + } + slices.sort { $0.depth < $1.depth } + let step = (slices[slices.count - 1].depth - slices[0].depth) / Double(slices.count - 1) + guard step > 0.001, zip(slices, slices.dropFirst()).allSatisfy({ + abs($1.depth - $0.depth - step) <= max(0.01, step * 0.02) + }) else { throw DICOMError.geometry } + spacing = SIMD3(basis.spacing.x, basis.spacing.y, step) + pixels = slices.flatMap(\.pixels) + } + minimum = pixels.min() ?? 0 + maximum = pixels.max() ?? 1 + } + + func count(_ plane: Plane) -> Int { + switch plane { + case .slices: return size.z + case .coronal: return size.y + case .sagittal: return size.x + } + } + + func image(_ plane: Plane, index: Int, center: Float, span: Float) -> (CGImage, Double)? { + let values: [Float] + let width: Int + let height: Int + let pitch = spacing ?? SIMD3(repeating: 1) + let aspect: Double + switch plane { + case .slices: + width = size.x + height = size.y + let start = index * width * height + values = Array(pixels[start..<(start + width * height)]) + aspect = Double(width) * pitch.x / (Double(height) * pitch.y) + case .coronal: + width = size.x + height = size.z + values = (0.. PatientImage { + guard let position = patients.firstIndex(where: { $0.id == patientID }) else { + throw LibraryError.patientMissing + } + let accessed = sources.filter { $0.startAccessingSecurityScopedResource() } + defer { accessed.forEach { $0.stopAccessingSecurityScopedResource() } } + _ = try DICOMVolume(urls: sources) + try prepareDirectory() + let name = sources.count == 1 ? sources[0].lastPathComponent : "Серия DICOM (\(sources.count) срезов)" + let image = PatientImage(id: UUID(), name: name, importedAt: Date(), dicomCount: sources.count) + let folder = url(for: image) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false) + do { + for (source, destination) in zip(sources, dicomURLs(for: image)) { + try FileManager.default.copyItem(at: source, to: destination) + } + var updated = patients + updated[position].images.insert(image, at: 0) + try save(updated) + } catch { + try? FileManager.default.removeItem(at: folder) + throw error + } + return image + } + + func dicomURLs(for image: PatientImage) -> [URL] { + (0..<(image.dicomCount ?? 0)).map { + url(for: image).appendingPathComponent("slice-\($0 + 1).dcm") + } + } + func url(for image: PatientImage) -> URL { directory.appendingPathComponent(image.id.uuidString) } diff --git a/Sources/EzDent/PatientWorkspace.swift b/Sources/EzDent/PatientWorkspace.swift index 0064a52..33b5502 100644 --- a/Sources/EzDent/PatientWorkspace.swift +++ b/Sources/EzDent/PatientWorkspace.swift @@ -96,7 +96,7 @@ struct PatientWorkspace: View { patientID = id } } - .fileImporter(isPresented: $showImporter, allowedContentTypes: [.image], allowsMultipleSelection: true, + .fileImporter(isPresented: $showImporter, allowedContentTypes: [.data], allowsMultipleSelection: true, onCompletion: importImages) .alert("Ошибка", isPresented: Binding( get: { errorMessage != nil }, @@ -128,7 +128,7 @@ struct PatientWorkspace: View { Divider() if record.images.isEmpty { - emptyState("Снимков пока нет", detail: "Добавьте JPEG, PNG, TIFF или другой поддерживаемый файл.", + emptyState("Снимков пока нет", detail: "Выберите изображение или все DICOM-срезы одной серии.", icon: "photo.on.rectangle") } else { let selected = record.images.first { $0.id == imageID } ?? record.images[0] @@ -144,8 +144,14 @@ struct PatientWorkspace: View { } .frame(width: 200) Divider() - ImageViewer(image: selected, url: library.url(for: selected)) { message in - errorMessage = message + Group { + if selected.dicomCount != nil { + DICOMViewer(urls: library.dicomURLs(for: selected)) + } else { + ImageViewer(image: selected, url: library.url(for: selected)) { message in + errorMessage = message + } + } } .id(selected.id) } @@ -169,7 +175,20 @@ struct PatientWorkspace: View { do { var errors: [String] = [] var firstImported: UUID? - for url in try result.get() { + let urls = try result.get() + let dicom = Set(urls.filter { url in + let access = url.startAccessingSecurityScopedResource() + defer { if access { url.stopAccessingSecurityScopedResource() } } + return ["dcm", "dicom"].contains(url.pathExtension.lowercased()) || DICOMImage.recognizes(url) + }) + if !dicom.isEmpty { + do { + firstImported = try library.importDICOM(from: urls.filter { dicom.contains($0) }, for: importPatientID).id + } catch { + errors.append(error.localizedDescription) + } + } + for url in urls where !dicom.contains(url) { do { let image = try library.importImage(from: url, for: importPatientID) firstImported = firstImported ?? image.id diff --git a/Sources/EzDent/VolumeProjection.swift b/Sources/EzDent/VolumeProjection.swift new file mode 100644 index 0000000..b4a9921 --- /dev/null +++ b/Sources/EzDent/VolumeProjection.swift @@ -0,0 +1,179 @@ +import MetalKit +import SwiftUI +import simd + +struct VolumeProjection: NSViewRepresentable { + let renderer: VolumeRenderer + let rotation: SIMD2 + let zoom: Float + let window: SIMD2 + let surface: Bool + + func makeNSView(context: Context) -> MTKView { + let view = MTKView(frame: .zero, device: renderer.device) + view.framebufferOnly = false + view.colorPixelFormat = .bgra8Unorm + view.isPaused = true + view.enableSetNeedsDisplay = true + view.delegate = renderer + return view + } + + func updateNSView(_ view: MTKView, context: Context) { + renderer.rotation = rotation + renderer.zoom = zoom + renderer.window = window + renderer.surface = surface + view.needsDisplay = true + } +} + +final class VolumeRenderer: NSObject, MTKViewDelegate { + let device: MTLDevice + private let queue: MTLCommandQueue + private let pipeline: MTLComputePipelineState + private let texture: MTLTexture + private let proportions: SIMD4 + private let range: SIMD2 + var rotation = SIMD2(0, 0) + var zoom: Float = 1 + var window = SIMD2(0, 1) + var surface = true + + init?(volume: DICOMVolume) { + guard let device = MTLCreateSystemDefaultDevice(), + let queue = device.makeCommandQueue(), + let library = try? device.makeLibrary(source: Self.shader, options: nil), + let function = library.makeFunction(name: "project"), + let pipeline = try? device.makeComputePipelineState(function: function), + let spacing = volume.spacing else { return nil } + + let original = volume.size + let longest = max(original.x, original.y, original.z) + let reduction = max(1, Double(longest) / 256) + let size = SIMD3(max(1, Int(Double(original.x) / reduction)), + max(1, Int(Double(original.y) / reduction)), + max(1, Int(Double(original.z) / reduction))) + let descriptor = MTLTextureDescriptor() + descriptor.textureType = .type3D + descriptor.pixelFormat = .r16Unorm + descriptor.width = size.x + descriptor.height = size.y + descriptor.depth = size.z + descriptor.usage = .shaderRead + guard let texture = device.makeTexture(descriptor: descriptor) else { return nil } + + let span = max(1, volume.maximum - volume.minimum) + var samples = [UInt16](repeating: 0, count: size.x * size.y * size.z) + for z in 0..(dimensions / scale) + proportions = SIMD4(normalized.x, normalized.y, normalized.z, volume.inverted ? 1 : 0) + range = SIMD2(volume.minimum, span) + self.device = device + self.queue = queue + self.pipeline = pipeline + self.texture = texture + } + + func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {} + + func draw(in view: MTKView) { + guard let drawable = view.currentDrawable, let commands = queue.makeCommandBuffer(), + encodeProjection(to: drawable.texture, using: commands) else { return } + commands.present(drawable) + commands.commit() + } + + func encodeProjection(to output: MTLTexture, using commands: MTLCommandBuffer) -> Bool { + guard let encoder = commands.makeComputeCommandEncoder() else { return false } + var box = proportions + var camera = SIMD4(rotation.x, rotation.y, zoom, surface ? 1 : 0) + var levels = SIMD4((window.x - window.y / 2 - range.x) / range.y, window.y / range.y, 0, 0) + encoder.setComputePipelineState(pipeline) + encoder.setTexture(texture, index: 0) + encoder.setTexture(output, index: 1) + encoder.setBytes(&box, length: 16, index: 0) + encoder.setBytes(&camera, length: 16, index: 1) + encoder.setBytes(&levels, length: 16, index: 2) + let group = MTLSize(width: 8, height: 8, depth: 1) + let width = output.width + let height = output.height + encoder.dispatchThreadgroups(MTLSize(width: (width + 7) / 8, height: (height + 7) / 8, depth: 1), + threadsPerThreadgroup: group) + encoder.endEncoding() + return true + } + + private static let shader = """ + #include + using namespace metal; + + kernel void project(texture3d volume [[texture(0)]], + texture2d output [[texture(1)]], + constant float4 &box [[buffer(0)]], constant float4 &camera [[buffer(1)]], + constant float4 &levels [[buffer(2)]], uint2 pixel [[thread_position_in_grid]]) { + if (pixel.x >= output.get_width() || pixel.y >= output.get_height()) return; + float2 size = float2(output.get_width(), output.get_height()); + float2 xy = (float2(pixel) + 0.5 - size * 0.5) * (1.8 / min(size.x, size.y)) / camera.z; + float sy = sin(camera.x), cy = cos(camera.x); + float sx = sin(camera.y), cx = cos(camera.y); + float3 origin = float3(cy * xy.x + sy * sx * xy.y, cx * xy.y, -sy * xy.x + cy * sx * xy.y); + float3 ray = float3(sy * cx, -sx, cy * cx); + float3 safeRay = select(ray, copysign(float3(0.00001), ray), abs(ray) < 0.00001); + float3 hitA = (-box.xyz * 0.5 - origin) / safeRay; + float3 hitB = ( box.xyz * 0.5 - origin) / safeRay; + float3 nearHit = min(hitA, hitB), farHit = max(hitA, hitB); + float enter = max(nearHit.x, max(nearHit.y, nearHit.z)); + float leave = min(farHit.x, min(farHit.y, farHit.z)); + float intensity = 0; + if (leave > enter) { + constexpr sampler sampleVolume(coord::normalized, address::clamp_to_edge, filter::linear); + const int steps = 320; + float extreme = box.w > 0 ? 1 : 0; + for (int i = 0; i < steps; ++i) { + float t = mix(enter, leave, (float(i) + 0.5) / float(steps)); + float3 samplePosition = (origin + t * ray) / box.xyz + 0.5; + float value = volume.sample(sampleVolume, samplePosition).r; + if (camera.w > 0) { + float threshold = levels.x + levels.y * 0.5; + if (box.w > 0 ? value > threshold : value < threshold) continue; + float3 pitch = 1.0 / float3(volume.get_width(), volume.get_height(), volume.get_depth()); + float3 dx = float3(pitch.x, 0, 0), dy = float3(0, pitch.y, 0), dz = float3(0, 0, pitch.z); + float3 gradient = float3( + volume.sample(sampleVolume, samplePosition + dx).r - volume.sample(sampleVolume, samplePosition - dx).r, + volume.sample(sampleVolume, samplePosition + dy).r - volume.sample(sampleVolume, samplePosition - dy).r, + volume.sample(sampleVolume, samplePosition + dz).r - volume.sample(sampleVolume, samplePosition - dz).r + ) / (box.xyz * pitch); + float magnitude = length(gradient); + float light = magnitude > 0.00001 ? abs(dot(gradient / magnitude, ray)) : 0.65; + intensity = 0.23 + 0.77 * light; + break; + } + extreme = box.w > 0 ? min(extreme, value) : max(extreme, value); + } + if (camera.w == 0) { + intensity = clamp((extreme - levels.x) / max(levels.y, 0.000001), 0.0, 1.0); + if (box.w > 0) intensity = 1 - intensity; + } + } + output.write(float4(float3(intensity), 1), pixel); + } + """ +}