forked from niivue/niivue-niimath
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
241 lines (237 loc) · 8.03 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import { Niivue, NVMeshUtilities } from '@niivue/niivue'
class NiiMathWrapper {
constructor(workerScript) {
this.worker = new Worker(workerScript)
}
niimath(niiBuffer, operationsText) {
return new Promise((resolve, reject) => {
const niiBlob = new Blob([niiBuffer], { type: 'application/octet-stream' })
const inName = 'input.nii'; // or derive from context
let outName = inName
if (operationsText.includes("-mesh")) {
outName = 'output.mz3'; // or derive from context
}
const args = operationsText.trim().split(/\s+/)
args.unshift(inName)
args.push(outName)
const file = new File([niiBlob], inName)
this.worker.onmessage = (e) => {
if (e.data.blob instanceof Blob) {
const reader = new FileReader()
reader.onload = () => {
//resolve({ arrayBuffer: reader.result, outName: e.data.outName, exitCode: e.data.exitCode })
resolve(reader.result)
}
reader.onerror = () => {
reject(new Error('Failed to read the Blob as an ArrayBuffer'))
}
reader.readAsArrayBuffer(e.data.blob)
} else {
reject(new Error('Expected Blob from worker'))
}
}
this.worker.onerror = (e) => {
reject(new Error(e.message))
}
this.worker.postMessage({ blob: file, cmd: args, outName: outName })
})
}
terminate() {
this.worker.terminate()
}
}
async function main() {
const wrapper = new NiiMathWrapper('./niimathWorker.js')
const NiimathWorker = await new Worker('./niimathWorker.js')
const loadingCircle = document.getElementById('loadingCircle')
let startTime = Date.now()
function removeExtension(filename) {
if (filename.endsWith('.gz')) {
filename = filename.slice(0, -3)
}
let lastDotIndex = filename.lastIndexOf('.')
if (lastDotIndex !== -1) {
filename = filename.slice(0, lastDotIndex)
}
return filename
}
saveImageBtn.onclick = function () {
if ((nv1.volumes.length < 1) && (nv1.meshes.length < 1)) {
window.alert('No volume open: you can open one using the "Volume" menu. Alternatively, drag and drop a image file.')
}
nv1.volumes[0].saveToDisk('niimath.nii')
if (nv1.volumes.length > 1) {
nv1.volumes[1].saveToDisk('overlay.nii')
}
}
saveMeshBtn.onclick = function () {
if (nv1.meshes.length < 1) {
window.alert('No mesh open: you can create one with a "mesh" operation. Alternatively, drag and drop a mesh file.')
} else {
saveDialog.show()
}
}
applySaveBtn.onclick = function () {
if (nv1.meshes.length < 1) {
return
}
let format = 'obj'
if (formatSelect.selectedIndex === 0) {
format = 'mz3'
}
if (formatSelect.selectedIndex === 2) {
format = 'stl'
}
NVMeshUtilities.saveMesh(nv1.meshes[0].pts, nv1.meshes[0].tris, `mesh.${format}`, true)
}
NiimathWorker.onmessage = async function (e) {
if (e.data.blob instanceof Blob) {
const reader = new FileReader()
reader.onload = async () => {
loadingCircle.classList.add('hidden')
const outName = e.data.outName || 'test.nii'
if (outName.endsWith('.mz3')) {
if (nv1.meshes.length > 0) {
nv1.removeMesh(nv1.meshes[0])
}
nv1.loadFromArrayBuffer(reader.result, outName)
} else {
if (nv1.volumes.length > 1) {
nv1.removeVolume(nv1.volumes[1])
}
if (overlayCheck.checked) {
await nv1.loadFromArrayBuffer(reader.result, outName)
nv1.volumes[1].opacity = 0.5
nv1.setColormap(nv1.volumes[1].id, 'red')
} else {
if (nv1.volumes.length > 0) {
nv1.removeVolume(nv1.volumes[0])
}
nv1.loadFromArrayBuffer(reader.result, outName)
}
nv1.setSliceType(nv1.sliceTypeMultiplanar)
}
let str = ` ${Date.now() - startTime}ms`
document.getElementById('location').innerHTML = str
}
reader.readAsArrayBuffer(e.data.blob)
}
}
processBtn2.onclick = async function () {
const niiBuffer = await nv1.saveImage().buffer
loadingCircle.classList.remove('hidden')
const arrayBuffer = await wrapper.niimath(niiBuffer, operationsText.value)
loadingCircle.classList.add('hidden')
const isMz3 = new Uint8Array(arrayBuffer)[0] === 77 && new Uint8Array(arrayBuffer)[1] === 90
if (isMz3) {
nv1.removeMesh(nv1.meshes[0])
await nv1.loadFromArrayBuffer(arrayBuffer, 'test.mz3')
} else {
nv1.removeVolume(nv1.volumes[0])
await nv1.loadFromArrayBuffer(arrayBuffer, 'test.nii')
}
}
processBtn.onclick = async function () {
if (nv1.meshes.volumes < 1) {
window.alert("No volume open for saving.")
return
}
let inName = removeExtension(nv1.volumes[0].name) + '.nii'
let outName = inName
if (operationsText.value.includes("-mesh")) {
outName = removeExtension(nv1.volumes[0].name) + '.mz3'
}
let args = operationsText.value.trim().split(/\s+/)
args.unshift(inName)
args.push(outName)
startTime = Date.now()
const niiBuffer = await nv1.saveImage().buffer
loadingCircle.classList.remove('hidden')
let nii = await new Blob([niiBuffer], {
type: 'application/octet-stream'
})
let fileNii = await new File([nii], inName)
NiimathWorker.postMessage({
blob: fileNii,
cmd: args,
outName: outName
})
}
operationSelect.onchange = function () {
operationsText.value = operationSelect.value
}
volumeSelect.onchange = async function () {
const selectedOption = volumeSelect.options[volumeSelect.selectedIndex]
const txt = selectedOption.text
if (volumeSelect.selectedIndex > 15) {
nv1.volumes = []
let fnm = 'https://niivue.github.io/niivue/images/' + txt
nv1.loadMeshes([{ url: fnm }])
return
}
let fnm = './' + txt
if (volumeSelect.selectedIndex > 7) {
fnm = 'https://niivue.github.io/niivue-demo-images/' + txt
}
if (nv1.meshes.length > 0) {
nv1.removeMesh(nv1.meshes[0])
}
nv1.volumes = []
fnm += '.nii.gz'
nv1.loadVolumes([{ url: fnm }])
}
simplifyBtn.onclick = function () {
if (nv1.meshes.length < 1) {
window.alert('No mesh open to simplify. Drag and drop a mesh or create a mesh from a voxel based image using a mesh operation.')
} else {
simplifyDialog.show()
}
}
applySimpleBtn.onclick = function () {
startTime = Date.now()
loadingCircle.classList.remove('hidden')
const shrinkValue = Math.min(Math.max(Number(shrinkSimplePct.value) / 100, 0.01), 1)
if (shrinkValue >= 1)
return
const verts = nv1.meshes[0].pts.slice()
const tris = nv1.meshes[0].tris.slice()
const meshBuffer = NVMeshUtilities.createMZ3(verts, tris, false)
let mz3 = new Blob([meshBuffer], {
type: 'application/octet-stream'
})
let inName = 'mesh.mz3'
let fileMz3 = new File([mz3], inName)
let outName = 'mesh.mz3'
let ops = 'niimath '+inName+' -r 0.1 '+outName
NiimathWorker.postMessage({
blob: fileMz3,
outName: outName,
cmd: ops,
})
}
moreButton.onclick = function () {
window.open('https://github.com/niivue/niivue-niimath#commands')
}
function handleLocationChange(data) {
document.getElementById('location').innerHTML = ' ' + data.string
}
const defaults = {
onLocationChange: handleLocationChange,
backColor: [0.2, 0.2, 0.3, 1],
show3Dcrosshair: true
}
const nv1 = new Niivue(defaults)
nv1.onImageLoaded = () => {
nv1.setSliceType(nv1.sliceTypeMultiplanar)
}
nv1.attachToCanvas(gl1)
nv1.isAlphaClipDark = true
nv1.setClipPlane([0.2, 0, 120])
nv1.opts.dragMode = nv1.dragModes.pan
nv1.setRenderAzimuthElevation(245, 15)
nv1.opts.multiplanarForceRender = true
nv1.opts.yoke3Dto2DZoom = true
nv1.setInterpolation(true)
await nv1.loadVolumes([{ url: './mni152.nii.gz' }])
}
main()