Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
1613 lines (1472 loc) · 68 KB
/
Copy pathmain.js
File metadata and controls
1613 lines (1472 loc) · 68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { installSculptEditor } from "./sculpt/editor.js";
import { Niivue } from "@niivue/niivue";
import { runInference as runInferenceTfjsMain } from "./brainchop-mainthread.js";
import { runInferenceWebGpu } from "./inference-webgpu.js";
import { inferenceModelsList, brainChopOpts } from "./brainchop-parameters.js";
import { localSystemDetails } from "./brainchop-diagnostics.js";
import MyWorker from "./brainchop-webworker.js?worker";
import { installResponsiveLayout } from "./responsive-layout.js";
import { installTouchViewControls } from "./touch-view.js";
// --- Backend State ---
let gpuDevice = null;
let isWebGpuAvailable = false;
let lastInferenceModelEntry = null;
// --- Backend fallback chain state -----------------------------------------
// runSelectedInference() tries WebGPU, then the native WebGL2 runner, then the
// tfjs worker (fast, then seqConv), then the main thread. Every one of those
// stages reports its own failure through callbackUI's modalMessage, which used
// to pop a blocking window.alert -- so a user on a machine where WebGPU is
// unavailable got "WebGPU Error: ..." and then a perfectly good segmentation
// from the next backend. An earlier backend giving up is a console-level event.
// Messages are collected here and only surfaced if the whole chain fails.
let suppressBackendModals = false;
let backendAttemptMessages = [];
// --- DEBUG OVERRIDE -------------------------------------------------------
// Normally false: WebGPU is used when available, WebGL2 is the fallback.
// Set true to force every model through the WebGL2 (WebWorker / tfjs) backend
// for debugging/benchmarking the fallback path. See the
// `isWebGpuAvailable && !FORCE_WEBGL2_TESTING` guard in runSelectedInference().
const FORCE_WEBGL2_TESTING = new URLSearchParams(window.location.search).get("backend") === "webgl2";
// Set true to skip the NATIVE WebGL2 runner (webgl2_runners/) and force the old
// tfjs WebWorker path. This is the A/B control for the native runner: with
// FORCE_WEBGL2_TESTING=true, flipping this false/true switches between the two
// WebGL2 implementations on the same machine and the same model, which is the
// only comparison that settles whether the port is worth it.
const FORCE_TFJS_WEBGL_TESTING = false;
// The NATIVE WebGL2 runner (webgl2_runners/) is LIVE. It is the whole point of
// that code: when WebGPU is missing -- Firefox, older Safari, most Linux browsers,
// many phones -- this is what makes brainchop fast instead of a several-minute
// crawl. 8.03 s for model16chan18cls at full 256^3 on an M1, roughly brainchopC
// parity, against a tfjs path that on Firefox cannot even reach its dense path for
// any GroupNorm model (see TASK_webgl2_native_runner.md section 2b).
//
// Shipping it is safe because it DECLINES rather than breaks: runInferenceWebGl2
// rejects on an unsupported device, a missing descriptor or safetensors, a GL
// error, a lost context, non-finite layer-1 activations, or an all-zero volume --
// and every rejection falls through to the tfjs worker below, which can still run
// every model. So the worst case is exactly the old behaviour plus a console line.
//
// The import stays DYNAMIC on purpose, and not to hide the feature: the WebGPU
// block above returns on success, so a WebGPU user never fetches this chunk or the
// second tfjs copy its worker pulls in. Same reasoning as brainchopC probing
// before it fetches its WebGL2 module.
//
// Outstanding: label parity against the WebGPU runner has not been diffed
// systematically. Set FORCE_WEBGL2_TESTING below to compare the two on one volume.
const ENABLE_NATIVE_WEBGL2 = true;
// --------------------------------------------------------------------------
/**
* Detects WebGPU support and initializes the device.
* Provides detailed diagnostics for troubleshooting.
*/
async function initializeBackend() {
const diagnostics = {
secureContext: window.isSecureContext,
navigatorGpuExists: 'gpu' in navigator,
adapterObtained: false,
deviceObtained: false,
f16Support: false,
error: null
};
// Check secure context first
if (!window.isSecureContext) {
console.warn('WebGPU requires a secure context (HTTPS or localhost).');
console.warn('Current origin:', window.location.origin);
}
if ('gpu' in navigator) {
try {
console.log('Requesting WebGPU adapter...');
const adapter = await navigator.gpu.requestAdapter();
if (adapter) {
diagnostics.adapterObtained = true;
console.log('WebGPU adapter obtained:', adapter);
// Log adapter info if available
if (adapter.info) {
console.log('Adapter info:', adapter.info);
}
// Log adapter limits
console.log('Adapter limits:', {
maxBufferSize: adapter.limits.maxBufferSize,
maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize,
maxComputeWorkgroupsPerDimension: adapter.limits.maxComputeWorkgroupsPerDimension
});
// Request the adapter's full limits. The default device limits cap
// maxComputeInvocationsPerWorkgroup at 256, but BEAM-tuned runners
// (e.g. dkatlas24) emit workgroups of 512-1024 invocations, which fail
// to create a ComputePipeline unless we opt into the higher limit here.
// Requesting the adapter's reported maximum is always valid.
const requiredLimits = {
maxBufferSize: adapter.limits.maxBufferSize,
maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize,
maxComputeInvocationsPerWorkgroup: adapter.limits.maxComputeInvocationsPerWorkgroup,
maxComputeWorkgroupSizeX: adapter.limits.maxComputeWorkgroupSizeX,
maxComputeWorkgroupSizeY: adapter.limits.maxComputeWorkgroupSizeY,
maxComputeWorkgroupSizeZ: adapter.limits.maxComputeWorkgroupSizeZ,
maxComputeWorkgroupStorageSize: adapter.limits.maxComputeWorkgroupStorageSize,
maxComputeWorkgroupsPerDimension: adapter.limits.maxComputeWorkgroupsPerDimension
};
const hasF16 = adapter.features.has("shader-f16");
diagnostics.f16Support = hasF16;
const requiredFeatures = hasF16 ? ["shader-f16"] : [];
gpuDevice = await adapter.requestDevice({ requiredLimits, requiredFeatures });
diagnostics.deviceObtained = true;
isWebGpuAvailable = true;
const f16Status = hasF16 ? "enabled" : "not available";
console.log(`✓ WebGPU initialized successfully. F16: ${f16Status}`);
} else {
console.warn('WebGPU adapter request returned null.');
console.warn('This typically means:');
console.warn(' - Safari: WebGPU feature flags not enabled in Settings > Feature Flags');
console.warn(' - Unsupported GPU hardware');
console.warn(' - GPU drivers need updating');
diagnostics.error = 'Adapter returned null';
}
} catch (e) {
diagnostics.error = e.message;
console.error('WebGPU initialization error:', e);
// Provide Safari-specific guidance
if (navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome')) {
console.warn('Safari detected. To enable WebGPU:');
console.warn(' 1. Open Safari Settings/Preferences');
console.warn(' 2. Go to Advanced tab, enable "Show features for web developers"');
console.warn(' 3. Go to Feature Flags tab');
console.warn(' 4. Enable: WebGPU, GPU Process: DOM Rendering, GPU Process: Canvas Rendering');
console.warn(' 5. Restart Safari');
}
}
} else {
console.warn('navigator.gpu not found. WebGPU API is not available in this browser.');
diagnostics.error = 'navigator.gpu not found';
// Provide Firefox-specific guidance
if (navigator.userAgent.includes('Firefox')) {
console.warn('Firefox detected. To enable WebGPU in about:config:');
console.warn(' 1. Set dom.webgpu.enabled = true');
console.warn(' 2. Set gfx.webgpu.ignore-blocklist = true');
console.warn(' 3. Restart Firefox');
}
}
// Update UI with backend status
// While FORCE_WEBGL2_TESTING is on, report WebGL even if WebGPU initialized,
// so the indicator matches the path actually used.
updateBackendStatusUI(isWebGpuAvailable && !FORCE_WEBGL2_TESTING, diagnostics);
if (!isWebGpuAvailable) {
console.log('Falling back to WebGL backend.');
}
// Store diagnostics for later access
window.webgpuDiagnostics = diagnostics;
return diagnostics;
}
/**
* Updates the UI to display the current backend status.
*/
function updateBackendStatusUI(webgpuAvailable, diagnostics) {
const statusEl = document.getElementById('backendStatus');
if (!statusEl) {
console.log('Backend status element not found in DOM');
return;
}
if (webgpuAvailable) {
const f16Text = diagnostics.f16Support ? ' (F16)' : '';
statusEl.textContent = `WebGPU${f16Text}`;
statusEl.style.color = '#4CAF50'; // Green
statusEl.title = 'WebGPU backend active - fastest performance';
} else {
statusEl.textContent = 'WebGL';
statusEl.style.color = '#FF9800'; // Orange
// Build helpful tooltip
let tooltip = 'WebGL backend (fallback)';
if (diagnostics.error) {
tooltip += `\nReason: ${diagnostics.error}`;
}
if (!diagnostics.secureContext) {
tooltip += '\n⚠ Not a secure context (HTTPS required)';
}
if (navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome')) {
tooltip += '\n\nTo enable WebGPU in Safari:\n1. Settings > Feature Flags\n2. Enable WebGPU flags\n3. Restart Safari';
}
if (navigator.userAgent.includes('Firefox')) {
tooltip += '\n\nTo enable WebGPU in Firefox:\n1. about:config > dom.webgpu.enabled = true\n2. gfx.webgpu.ignore-blocklist = true\n3. Restart Firefox';
}
statusEl.title = tooltip;
}
}
async function main() {
let diagnosticsString = "";
let missingLabelStatus = "";
let chopWorker;
// Raw label names / colors for the current segmentation (index -> value), used by "Save Stats".
let lastSegLabelNames = null;
let lastSegColors = null; // { R:[], G:[], B:[] }
// --- Single-label isolation --------------------------------------------
// Alt/Option-click a region in a 2D panel to show ONLY that label across
// the X/Y/Z panels and the 3D render. Alt-click the same region again (or
// Alt-click background) to restore all labels. It's a pure display toggle:
// we only flip per-label alpha in the overlay color LUT, never the voxels.
// Option/Alt is chosen because niivue already binds Shift+drag and
// Ctrl+drag to its own drag modes (and Ctrl-click is a context menu on
// macOS), whereas altKey is free for in-canvas clicks.
const ISOLATE_MODIFIER = "altKey";
let isolatedLabel = null; // label value shown alone, or null = show all
let originalSegImg = null; // pristine label voxels, for restore + stats
let isolationStats = null; // { lines:[...], color:[r,g,b,a] } drawn as a fixed HUD
const HUD_TEXT_SCALE = 0.9; // relative to niivue fontPx
let nativeInputNV = null; // volume as loaded (native grid), before conform
let nativeInputName = "input.nii.gz";
const sampleSelect = document.getElementById("sampleSelect");
const maskToggle = document.getElementById("maskToggle");
const modelRunButton = document.getElementById("modelRunButton");
let sculptEditor = null;
let lastBrainMask = null;
let lastExtractedBrain = null;
function clearCachedResult() {
sculptEditor?.invalidate();
lastBrainMask = null;
lastExtractedBrain = null;
sculptEditor?.updateAvailability();
lastInferenceModelEntry = null;
if (maskToggle) {
maskToggle.checked = false;
maskToggle.disabled = true;
}
}
// --- Drag mode: segmented control (data-drag maps to nv.opts.dragMode) ---
const dragSegmented = document.getElementById("dragSegmented");
if (dragSegmented) {
dragSegmented.querySelectorAll("button").forEach((btn) => {
btn.onclick = () => {
nv1.opts.dragMode = parseInt(btn.dataset.drag, 10);
dragSegmented.querySelectorAll("button").forEach((b) =>
b.classList.toggle("active", b === btn));
};
});
}
// --- Draw tools: popover with pen selection + apply actions ---
const drawBtn = document.getElementById("drawBtn");
const drawPopover = document.getElementById("drawPopover");
const penRow = document.getElementById("penRow");
const drawApplyRow = document.getElementById("drawApplyRow");
function openDrawPopover(open) {
if (!drawPopover) return;
drawPopover.hidden = !open;
if (drawBtn) drawBtn.setAttribute("aria-expanded", String(open));
}
function setPen(mode) {
nv1.setDrawingEnabled(mode >= 0);
if (mode >= 0) nv1.setPenValue(mode & 7, mode > 7);
if (penRow) penRow.querySelectorAll(".chip").forEach((b) =>
b.classList.toggle("active", parseInt(b.dataset.pen, 10) === mode));
}
async function applyDraw(mode) {
if (nv1.volumes.length < 2) {
window.alert("No segmentation open (run a model first).");
return;
}
if (sculptEditor?.active) return;
if (mode === 0) { // undo
nv1.drawUndo();
return;
}
if (!nv1.drawBitmap) {
window.alert("Nothing drawn yet — pick a pen and draw on the image first.");
return;
}
const img = nv1.volumes[1].img;
// Pass RAS drawing bytes directly to the writer: NiiVue 0.62 saveImage
// and its NVImage writer otherwise both reorient non-RAS drawings.
const draw = await nv1.volumes[0].saveToDisk("", nv1.drawBitmap);
const niiHdrBytes = 352;
const nvox = img.length;
if (mode === 1) { // append
for (let i = 0; i < nvox; i++) if (draw[niiHdrBytes + i] > 0) img[i] = 1;
}
if (mode === 2) { // remove
for (let i = 0; i < nvox; i++) if (draw[niiHdrBytes + i] > 0) img[i] = 0;
}
// Drawing and sculpting share the binary mask; extracted intensities derive
// from that mask instead of becoming a separately edited output.
if (lastBrainMask && maskToggle?.checked) {
lastBrainMask.set(img);
for (let i = 0; i < nvox; i++) lastExtractedBrain[i] = nv1.volumes[0].img[i] * lastBrainMask[i];
} else if (lastBrainMask) {
// Applying a drawing while viewing extracted intensities still edits the mask.
for (let i = 0; i < nvox; i++) if (draw[niiHdrBytes + i] > 0) {
lastBrainMask[i] = mode === 1 ? 1 : 0;
lastExtractedBrain[i] = nv1.volumes[0].img[i] * lastBrainMask[i];
}
}
sculptEditor?.invalidate();
nv1.closeDrawing();
nv1.updateGLVolume();
nv1.setDrawingEnabled(false);
setPen(-1);
}
if (drawBtn) {
drawBtn.onclick = (e) => {
e.stopPropagation();
openDrawPopover(drawPopover.hidden);
};
}
if (penRow) {
penRow.querySelectorAll(".chip").forEach((btn) => {
btn.onclick = () => setPen(parseInt(btn.dataset.pen, 10));
});
}
if (drawApplyRow) {
drawApplyRow.querySelectorAll(".chip").forEach((btn) => {
btn.onclick = () => applyDraw(parseInt(btn.dataset.apply, 10));
});
}
// Close the popover on outside click / Escape.
document.addEventListener("click", (e) => {
if (!drawPopover || drawPopover.hidden) return;
if (!e.target.closest(".popover-wrap")) openDrawPopover(false);
});
document.addEventListener("keydown", (e) => {
if (e.key === "Escape") openDrawPopover(false);
});
// Dismiss any modal by clicking its backdrop.
const appDialogEl = document.getElementById("appDialog");
if (appDialogEl) {
appDialogEl.addEventListener("click", (e) => {
if (e.target === appDialogEl) appDialogEl.close();
});
}
aboutBtn.onclick = function () {
const aboutContent = `
<div style="text-align: left; font-size: 0.95em;">
<p><strong>🔒 Privacy First</strong><br>
Brainchomp runs entirely <strong>locally in your browser</strong>. Your imaging data never leaves your device.</p>
<p><strong>⌨️ Controls</strong><br>
• <strong>Drag & Drop</strong> a pre-conformed 256³ NIfTI file to open.<br>
• Use the <strong>example selector</strong> to switch between the bundled rodent MRI and mask.<br>
• Press <strong>C</strong> to cycle the clip-plane.<br>
• Press <strong>V</strong> to cycle through views.</p>
<p><strong>🐭 Rodent brain extraction</strong><br>
Skull-strip runs the 16-channel MeshNet once. Use the <strong>Mask</strong>
toggle to switch the overlay between the extracted brain and its
post-processed binary mask. The Save menu offers both outputs.</p>
<p><em>Inputs must already be 256 × 256 × 256. This version does not resample or conform them.</em></p>
</div>
`;
showModal("About Brainchomp", aboutContent);
};
diagnosticsBtn.onclick = function () {
let msg = diagnosticsString;
// If no inference run yet, show startup diagnostics
if (msg.length < 1 && window.webgpuDiagnostics) {
const d = window.webgpuDiagnostics;
msg = ":: Startup Diagnostics ::\n";
msg += `Secure Context: ${d.secureContext}\n`;
msg += `WebGPU Enabled: ${isWebGpuAvailable}\n`;
msg += `F16 Support: ${d.f16Support}\n`;
if (d.error) msg += `Error: ${d.error}\n`;
// Add browser info
msg += `User Agent: ${navigator.userAgent}\n`;
}
// If no inference run yet, show startup diagnostics
if (msg.length < 1 && window.webgpuDiagnostics) {
// ... (existing logic to build msg)
}
if (msg.length < 1) {
showModal("Diagnostics", "No diagnostic string generated: run a model to create diagnostics");
return;
}
// Logic for missing labels
let statusMsg = msg;
missingLabelStatus = missingLabelStatus.slice(0, -2);
if (missingLabelStatus !== "") {
if (statusMsg.includes('Status: OK')) {
statusMsg = statusMsg.replace('Status: OK', `Status: ${missingLabelStatus}`);
}
}
missingLabelStatus = "";
// ^ note: clipboard write is async but often works without await in loose contexts.
// Ideally we catch errors.
navigator.clipboard.writeText(statusMsg).then(() => {
showModal("Diagnostics", `<p>Diagnostics copied to clipboard</p><pre style="white-space: pre-wrap; font-family: monospace; font-size: 0.9em; overflow-x: auto;">${statusMsg}</pre>`);
}).catch(err => {
showModal("Diagnostics", `<p>Failed to copy to clipboard.</p><pre style="white-space: pre-wrap; font-family: monospace; font-size: 0.9em; overflow-x: auto;">${statusMsg}</pre>`);
});
};
opacitySlider0.oninput = function () {
nv1.setOpacity(0, opacitySlider0.value / 255);
nv1.updateGLVolume();
};
opacitySlider1.oninput = function () {
if (sculptEditor?.active) { nv1.setDrawOpacity(opacitySlider1.value / 255); return; }
nv1.setOpacity(1, opacitySlider1.value / 255);
};
async function ensureConformed() {
const nii = nv1.volumes[0];
const expected = 256 * 256 * 256;
const valid =
nii.dims[1] === 256 && nii.dims[2] === 256 && nii.dims[3] === 256
&& nii.img.length === expected;
if (valid) return;
throw new Error(
`Brainchomp currently requires a pre-conformed 256 × 256 × 256 NIfTI; received ${nii.dims[1]} × ${nii.dims[2]} × ${nii.dims[3]}.`
);
}
async function closeAllOverlays() {
while (nv1.volumes.length > 1) {
await nv1.removeVolume(nv1.volumes[1]);
}
}
// The segmentation overlay, only if it carries a discrete label LUT.
function segOverlay() {
return (nv1.volumes.length >= 2 && nv1.volumes[1].colormapLabel)
? nv1.volumes[1] : null;
}
function resetLabelIsolation() {
isolatedLabel = null;
originalSegImg = null;
isolationStats = null;
}
// Isolation works on the label DATA, not the color LUT: non-selected voxels
// are set to background (0). We tried hiding others via the LUT (alpha 0)
// instead, but niivue's 3D atlas shader anti-aliases each voxel's ALPHA from
// its 6 neighbours while keeping each voxel's own RGB — so hidden voxels
// touching the kept region borrowed alpha and smeared their color/glow onto
// the surface, burying the folds. Zeroing the data makes those voxels true
// background: the shader skips them, the T1 shows through the sulci, and the
// kept region keeps clean anti-aliased edges. Fully reversible — the pristine
// labels are restored from originalSegImg (also used for stats).
function applyLabelIsolation() {
const ov = segOverlay();
if (!ov) return;
if (originalSegImg === null) originalSegImg = ov.img; // capture pristine once
if (isolatedLabel === null) {
ov.img = originalSegImg;
isolationStats = null;
} else {
const src = originalSegImg;
const out = new src.constructor(src.length);
for (let i = 0; i < src.length; i++) out[i] = (src[i] === isolatedLabel) ? isolatedLabel : 0;
ov.img = out;
isolationStats = buildIsolationStats(isolatedLabel);
}
nv1.updateGLVolume();
}
// Full stats for one label, formatted as lines for the on-screen readout.
function buildIsolationStats(labelVal) {
const base = nv1.volumes[0];
const seg = originalSegImg || (nv1.volumes[1] && nv1.volumes[1].img);
if (!base || !seg) return null;
const pd = base.hdr.pixDims || [];
const voxMm3 = (pd[1] && pd[2] && pd[3]) ? pd[1] * pd[2] * pd[3] : 1;
const rows = computeLabelStats(base.img, seg, voxMm3);
const total = rows.reduce((s, r) => s + r.volume_mm3, 0);
const r = rows.find((x) => x.label === labelVal);
if (!r) return null;
const pct = total > 0 ? (r.volume_mm3 / total) * 100 : 0;
const lines = [
r.name,
`${fmtCm3(r.volume_mm3)} cm3 (${pct.toFixed(1)}% of brain)`,
`${r.voxels.toLocaleString()} voxels`,
`intensity ${r.mean.toFixed(0)} +/- ${r.stdev.toFixed(0)}`,
];
// Title in the region's own color, brightened for legibility on black.
let color = [1, 1, 1, 1];
if (lastSegColors && lastSegColors.R && lastSegColors.R[labelVal] != null) {
const br = (c) => Math.min(255, c * 0.55 + 130) / 255;
color = [br(lastSegColors.R[labelVal]), br(lastSegColors.G[labelVal]), br(lastSegColors.B[labelVal]), 1];
}
return { lines, color };
}
// Draw the isolated-region readout as fixed screen-space text in the empty
// top-left corner of the 3D render tile. Because it's drawn per-frame in
// canvas coordinates (not anchored in the scene), it stays put while the head
// rotates. niivue's drawText is single-line, so we lay out the lines by hand.
function drawIsolationHUD() {
if (isolatedLabel === null || !isolationStats || !segOverlay()) return;
const tile = nv1.screenSlices && nv1.screenSlices.find((s) => s.axCorSag === 4 /* RENDER */);
if (!tile) return;
const [L, T] = tile.leftTopWidthHeight; // canvas px, top-left origin
const gl = nv1.gl;
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
gl.enable(gl.BLEND);
const size = nv1.fontPx * HUD_TEXT_SCALE;
const lineH = size * 1.55;
const pad = nv1.fontPx * 0.6;
const x = L + pad;
const y = T + pad;
const white = [0.92, 0.92, 0.92, 1];
const { lines, color } = isolationStats;
nv1.drawText([x, y], lines[0], HUD_TEXT_SCALE, color);
for (let i = 1; i < lines.length; i++) {
nv1.drawText([x, y + i * lineH], lines[i], HUD_TEXT_SCALE, white);
}
}
// True (pristine) label under the crosshair, even while a region is isolated,
// so Alt-clicking a different region switches straight to it.
function labelUnderCursor() {
const ov = segOverlay();
if (!ov) return null;
const mm = nv1.frac2mm(nv1.scene.crosshairPos, 0, true);
const vox = ov.mm2vox(mm);
const cur = ov.img;
if (originalSegImg) ov.img = originalSegImg;
const v = Math.round(ov.getValue(vox[0], vox[1], vox[2], ov.frame4D));
ov.img = cur;
return v;
}
// Toggle isolation of a specific label value. Background (0) or the already
// isolated label restores the full view. Shared by Alt-click, the stats
// panel, and Esc.
function isolateLabel(labelVal) {
if (sculptEditor?.active) return;
if (!segOverlay()) return;
isolatedLabel = (labelVal === 0 || labelVal === isolatedLabel) ? null : labelVal;
applyLabelIsolation();
}
function handleIsolateClick(e) {
if (!e[ISOLATE_MODIFIER]) return;
if (!segOverlay()) return;
const lbl = labelUnderCursor();
if (lbl === null || Number.isNaN(lbl)) return;
isolateLabel(lbl);
e.preventDefault();
}
// Wrapper: owns the "is a fallback still possible" state for callbackUI.
async function runSelectedInference() {
if (suppressBackendModals || sculptEditor?.active) return; // already running or editing
suppressBackendModals = true;
sculptEditor?.updateAvailability();
if (modelRunButton) modelRunButton.disabled = true;
backendAttemptMessages = [];
try {
await runInferenceChain();
} catch (error) {
console.error("Inference could not start:", error);
showModal("Input not supported", escapeHtml(error?.message || String(error)));
} finally {
suppressBackendModals = false;
sculptEditor?.updateAvailability();
if (modelRunButton) modelRunButton.disabled = false;
}
}
async function runInferenceChain() {
const selectedModelIndex = modelSelect.value;
if (selectedModelIndex === "-1") return;
if (modelSelect.selectedIndex < 0) return;
await closeAllOverlays();
resetLabelIsolation(); // drop any active single-label view + its HUD
await ensureConformed();
const modelEntry = inferenceModelsList[selectedModelIndex];
const opts = { ...brainChopOpts };
// Fix URL construction to handle './' base correctly and allow subfolders
const rootUrl = new URL(import.meta.env.BASE_URL, window.location.href).href;
// Remove trailing slash if present to avoid double slashes when appending paths starting with /
opts.rootURL = rootUrl.endsWith('/') ? rootUrl.slice(0, -1) : rootUrl;
const niftiImage = nv1.volumes[0].img;
// 1. Try WebGPU (skipped while FORCE_WEBGL2_TESTING is true)
if (isWebGpuAvailable && !FORCE_WEBGL2_TESTING && modelEntry.webgpu_safetensor) {
console.log("Attempting WebGPU backend...");
// Get UI state for TTA
const currentModelEntry = { ...modelEntry, enableTTA: false };
try {
await runInferenceWebGpu(gpuDevice, opts, currentModelEntry, nv1.volumes[0].hdr, niftiImage, callbackImg, callbackUI);
return; // Success
} catch (e) {
console.error("WebGPU inference failed, falling back to WebWorker.", e);
}
}
// 1b. Try the NATIVE WebGL2 runner (webgl2_runners/): raw GLSL, 3D textures
// and MRT, bypassing tfjs entirely. Any refusal -- unsupported device, no
// descriptor, no safetensors, a GL error, an all-zero volume -- rejects and
// falls through to the tfjs worker below, which can still run every model.
if (ENABLE_NATIVE_WEBGL2 && !FORCE_TFJS_WEBGL_TESTING && modelEntry.webgpu_safetensor) {
try {
// Dynamic so WebGPU users never fetch this chunk (see ENABLE_NATIVE_WEBGL2).
const { runInferenceWebGl2, nativeWebgl2Available } = await import("./inference-webgl2.js");
if (nativeWebgl2Available()) {
console.log("Attempting native WebGL2 runner...");
await runInferenceWebGl2(opts, modelEntry, nv1.volumes[0].hdr, niftiImage, callbackImg, callbackUI);
return; // Success
}
console.log("Native WebGL2 unavailable here (no OffscreenCanvas/webgl2); using the tfjs worker.");
} catch (e) {
console.warn("Native WebGL2 declined or failed, falling back to the tfjs worker.", e.message);
}
}
// 2. Try WebWorker (WebGL)
console.log("Attempting WebWorker backend...");
if (typeof chopWorker !== "undefined") {
console.log("Worker is busy. Please wait.");
return;
}
const plainNiftiHeader = {
dims: nv1.volumes[0].hdr.dims,
datatypeCode: nv1.volumes[0].hdr.datatypeCode,
};
const runWorker = (useSeqConv) => {
return new Promise((resolve, reject) => {
const currentOpts = { ...opts, enableSeqConv: useSeqConv };
const currentModelEntry = { ...modelEntry, enableSeqConv: useSeqConv, enableTTA: false };
chopWorker = new MyWorker({ type: "module" });
chopWorker.postMessage({ opts: currentOpts, modelEntry: currentModelEntry, niftiHeader: plainNiftiHeader, niftiImage });
chopWorker.onmessage = function (event) {
const { cmd, message, progressFrac, modalMessage, statData, img, opts, modelEntry } = event.data;
if (cmd === "ui") {
if (modalMessage) {
chopWorker.terminate();
chopWorker = undefined;
// Check for failure status or error message
if (statData && statData.Status === 'Fail') {
reject(new Error(statData.Error_Type || modalMessage));
return;
}
// Some errors might be passed as modalMessage without statData
if (typeof modalMessage === 'string' && (modalMessage.toLowerCase().includes('fail') || modalMessage.toLowerCase().includes('error') || modalMessage.toLowerCase().includes('compatible') || modalMessage.toLowerCase().includes('texture') || modalMessage.toLowerCase().includes('maximum'))) {
reject(new Error(modalMessage));
return;
}
}
callbackUI(message, progressFrac, modalMessage, statData);
}
if (cmd === "img") {
chopWorker.terminate();
chopWorker = undefined;
callbackImg(img, opts, modelEntry);
resolve();
}
};
chopWorker.onerror = function (e) {
console.error("WebWorker failed", e);
chopWorker.terminate();
chopWorker = undefined;
reject(e);
};
});
};
try {
console.log("Attempting WebWorker with enableSeqConv: false");
await runWorker(false);
return;
} catch (e) {
console.warn("WebWorker (fast) failed, retrying with enableSeqConv: true", e);
// Explicitly terminate worker if it's still around
if (typeof chopWorker !== "undefined") {
chopWorker.terminate();
chopWorker = undefined;
}
// Delay to allow WebGL context cleanup
console.log("Waiting 1000ms for WebGL context cleanup...");
await new Promise(r => setTimeout(r, 1000));
try {
console.log("Attempting WebWorker with enableSeqConv: true");
await runWorker(true); // Retry with seqConv
return;
} catch (e2) {
console.error("WebWorker (slow) failed, falling back to Main Thread.", e2);
}
}
// 3. Fallback to Main Thread
console.log("Attempting Main Thread backend...");
const runMainThread = (useSeqConv) => {
return new Promise((resolve, reject) => {
const currentOpts = { ...opts, enableSeqConv: useSeqConv };
const currentModelEntry = { ...modelEntry, enableSeqConv: useSeqConv };
// Proxy callbackUI to intercept errors
const proxyCallbackUI = (message, progressFrac, modalMessage, statData) => {
if (statData && statData.Status === 'Fail') {
reject(new Error(statData.Error_Type || modalMessage || "Inference Failed"));
// We still call original callback to show error to user?
// Actually if we are falling back, we might NOT want to show the error yet?
// But the existing code shows it. Let's let it show for now, or maybe suppress if we are going to retry.
// For now, let's just reject.
} else if (modalMessage && typeof modalMessage === 'string' && (modalMessage.toLowerCase().includes('fail') || modalMessage.toLowerCase().includes('error') || modalMessage.toLowerCase().includes('compatible') || modalMessage.toLowerCase().includes('texture') || modalMessage.toLowerCase().includes('maximum'))) {
reject(new Error(modalMessage));
}
// If we are rejecting, we might want to prevent the UI from showing the error if we are going to retry.
// But modifying callbackUI logic deeply is risky.
// Let's just pass it through. The user might see "Error" then "Retrying..."
callbackUI(message, progressFrac, modalMessage, statData);
};
// Proxy callbackImg to resolve
const proxyCallbackImg = (img, opts, modelEntry) => {
callbackImg(img, opts, modelEntry);
resolve();
};
runInferenceTfjsMain(currentOpts, currentModelEntry, nv1.volumes[0].hdr, niftiImage, proxyCallbackImg, proxyCallbackUI)
.catch(e => reject(e));
});
};
try {
console.log("Attempting Main Thread with enableSeqConv: false");
await runMainThread(false);
} catch (e) {
console.warn("Main Thread (fast) failed, retrying with enableSeqConv: true", e);
await new Promise(r => setTimeout(r, 100)); // Small delay
try {
console.log("Attempting Main Thread with enableSeqConv: true");
await runMainThread(true);
} catch (e2) {
console.error("Main Thread (slow) failed.", e2);
showBackendFailure(e2);
}
}
}
modelSelect.onchange = runSelectedInference;
if (modelRunButton) {
modelRunButton.onclick = () => {
modelSelect.value = "0";
runSelectedInference();
};
}
if (maskToggle) {
maskToggle.onchange = () => {
if (!lastBrainMask) return;
renderCachedOutput().catch((error) => {
console.error("Could not switch result overlay:", error);
showModal("Overlay error", escapeHtml(error?.message || String(error)));
});
};
}
// backendSelect.onchange = runSelectedInference; // Removed
// --- Save actions -------------------------------------------------------
// Each action performs the pristine-label swap where relevant (isolation is
// a view-only state) so exports always contain the full segmentation.
function withPristineLabels(fn) {
const ov = segOverlay();
const restore = isolatedLabel !== null && ov && originalSegImg;
if (restore) ov.img = originalSegImg;
try {
return fn();
} finally {
if (restore) applyLabelIsolation();
}
}
async function saveCachedResult(kind) {
if (sculptEditor?.busy) return;
if (!lastBrainMask || !lastExtractedBrain) {
window.alert("No result to save (run Skull-strip first).");
return;
}
const outputVolume = await nv1.volumes[0].clone();
outputVolume.zeroImage();
Object.assign(outputVolume.hdr, { scl_inter: 0, scl_slope: 1 });
if (kind === "mask") {
outputVolume.img = lastBrainMask;
outputVolume.hdr.datatypeCode = 2; // DT_UINT8
outputVolume.hdr.numBitsPerVoxel = 8;
outputVolume.hdr.intent_code = 1002; // NIFTI_INTENT_LABEL
outputVolume.saveToDisk("brainmask.nii.gz");
return;
}
outputVolume.img = lastExtractedBrain;
outputVolume.hdr.intent_code = 0;
outputVolume.saveToDisk("skull_stripped_brain.nii.gz");
}
function saveConformedInput() {
if (nv1.volumes.length < 1) { window.alert("No image loaded."); return; }
nv1.volumes[0].saveToDisk("input.nii.gz");
}
async function saveScene() {
if (nv1.volumes.length < 1) { window.alert("No image loaded."); return; }
await withPristineLabels(async () => { await nv1.saveDocument("brainchomp.nvd"); });
}
// Native-space segmentation: reslice the conformed (256³, 1 mm) labels back
// onto the original input grid. See resliceLabelsToNative() for the method.
async function saveSegmentationNative() {
if (nv1.volumes.length < 2) { window.alert("No segmentation to save (run a model first)."); return; }
if (!nativeInputNV || !nativeInputNV.hdr || !nativeInputNV.hdr.affine) {
window.alert("Original input grid is unavailable — reload the image and try again.");
return;
}
callbackUI("Reslicing to native space…", 0);
await new Promise((r) => setTimeout(r, 30)); // let the status paint before the blocking loop
try {
const outNV = withPristineLabels(() => resliceLabelsToNative());
await outNV.saveToDisk("segmentation_native.nii.gz");
callbackUI("Saved native-space segmentation.", 1);
} catch (e) {
console.error("Native-space reslice failed:", e);
window.alert("Native-space export failed: " + (e && e.message ? e.message : e));
}
}
// Reslice the conformed overlay onto the native input grid.
//
// For a label map (segmentation): nearest-neighbour with 2× supersampling and
// a majority vote per output voxel — crisper categorical boundaries — written
// as Int16 tagged NIFTI_INTENT_LABEL.
// For an intensity output (e.g. skull-stripped brain): plain nearest-neighbour
// keeping the native datatype and NOT tagged as a label — it's an image.
//
// The native→conformed voxel map is built by probing niivue's own verified
// transforms at four basis points (origin + unit steps), so it is correct for
// any orientation without us re-deriving affine conventions. Validated: when
// the two grids are identical the map is the identity.
function resliceLabelsToNative() {
const seg = nv1.volumes[1];
const labels = seg.img; // pristine labels (see withPristineLabels)
const A = nativeInputNV.hdr.affine; // native storage-voxel -> mm (row-major 4x4)
const nx = nativeInputNV.hdr.dims[1], ny = nativeInputNV.hdr.dims[2], nz = nativeInputNV.hdr.dims[3];
const snx = seg.hdr.dims[1], sny = seg.hdr.dims[2], snz = seg.hdr.dims[3];
const applyAffine = (a, v) => [
a[0][0] * v[0] + a[0][1] * v[1] + a[0][2] * v[2] + a[0][3],
a[1][0] * v[0] + a[1][1] * v[1] + a[1][2] * v[2] + a[1][3],
a[2][0] * v[0] + a[2][1] * v[1] + a[2][2] * v[2] + a[2][3],
];
const applyGL = (m, v) => [ // gl-matrix mat4 is column-major
m[0] * v[0] + m[4] * v[1] + m[8] * v[2] + m[12],
m[1] * v[0] + m[5] * v[1] + m[9] * v[2] + m[13],
m[2] * v[0] + m[6] * v[1] + m[10] * v[2] + m[14],
];
// native storage voxel -> conformed storage voxel (fractional)
const f = (v) => {
const mm = applyAffine(A, v);
const ras = seg.mm2vox([mm[0], mm[1], mm[2]], true); // mm -> conformed RAS voxel
return applyGL(seg.toRASvox, [ras[0], ras[1], ras[2]]); // RAS -> storage voxel
};
const o = f([0, 0, 0]);
const ex = f([1, 0, 0]).map((x, i) => x - o[i]);
const ey = f([0, 1, 0]).map((x, i) => x - o[i]);
const ez = f([0, 0, 1]).map((x, i) => x - o[i]);
// Is this a discrete label map (segmentation) or a continuous intensity
// output (e.g. skull-stripped brain from Brain_Extraction/mindgrab)? Label
// overlays carry a colormapLabel; intensity ones use a plain colormap.
const isLabel = !!seg.colormapLabel;
const nvox = nx * ny * nz;
const outNV = nativeInputNV.clone();
const sample = (x, y, z) =>
(x >= 0 && x < snx && y >= 0 && y < sny && z >= 0 && z < snz)
? labels[x + y * snx + z * snx * sny] : 0;
if (isLabel) {
// 2× supersample: 8 offsets at ±0.25 native voxel, in conformed space.
const deltas = [];
for (const dx of [-0.25, 0.25])
for (const dy of [-0.25, 0.25])
for (const dz of [-0.25, 0.25])
deltas.push([
dx * ex[0] + dy * ey[0] + dz * ez[0],
dx * ex[1] + dy * ey[1] + dz * ez[1],
dx * ex[2] + dy * ey[2] + dz * ez[2],
]);
const out = new Int16Array(nvox);
let maxLabel = 0;
const tv = new Int32Array(8), tc = new Int32Array(8); // majority tally (≤8 distinct)
let idx = 0;
for (let k = 0; k < nz; k++) {
for (let j = 0; j < ny; j++) {
let bx = o[0] + j * ey[0] + k * ez[0];
let by = o[1] + j * ey[1] + k * ez[1];
let bz = o[2] + j * ey[2] + k * ez[2];
for (let i = 0; i < nx; i++) {
let nt = 0;
for (let s = 0; s < 8; s++) {
const lbl = sample(
Math.round(bx + deltas[s][0]),
Math.round(by + deltas[s][1]),
Math.round(bz + deltas[s][2]));
let t = -1;
for (let q = 0; q < nt; q++) if (tv[q] === lbl) { t = q; break; }
if (t < 0) { tv[nt] = lbl; tc[nt] = 1; nt++; } else { tc[t]++; }
}
let best = tv[0], bc = tc[0];
for (let q = 1; q < nt; q++) if (tc[q] > bc) { bc = tc[q]; best = tv[q]; }
if (best > maxLabel) maxLabel = best;
out[idx++] = best;
bx += ex[0]; by += ex[1]; bz += ex[2];
}
}
}
outNV.hdr.datatypeCode = 4; // DT_INT16
outNV.hdr.numBitsPerVoxel = 16;
outNV.hdr.scl_slope = 1;
outNV.hdr.scl_inter = 0;
outNV.hdr.cal_min = 0;
outNV.hdr.cal_max = maxLabel;
outNV.hdr.intent_code = 1002; // NIFTI_INTENT_LABEL
outNV.img = out;
} else {
// Intensity output (skull-stripped brain): plain nearest-neighbour, keep
// the native datatype, and do NOT tag as LABEL — this is an image.
const out = outNV.img; // native-datatype typed array, length nvox
out.fill(0);
outNV.hdr.scl_slope = 1;
outNV.hdr.scl_inter = 0;
let idx = 0;
for (let k = 0; k < nz; k++) {
for (let j = 0; j < ny; j++) {
let bx = o[0] + j * ey[0] + k * ez[0];
let by = o[1] + j * ey[1] + k * ez[1];
let bz = o[2] + j * ey[2] + k * ez[2];
for (let i = 0; i < nx; i++) {
out[idx++] = sample(Math.round(bx), Math.round(by), Math.round(bz));
bx += ex[0]; by += ex[1]; bz += ex[2];
}
}
}
}
return outNV;
}
const SAVE_OPTIONS = [
{ act: () => saveCachedResult("brain"), title: "Skull-stripped brain", sub: "input intensities with background set to zero", need: "result" },
{ act: () => saveCachedResult("mask"), title: "Brain mask", sub: "binary mask, including accepted edits", need: "result" },
{ act: saveConformedInput, title: "Input volume", sub: "the currently loaded 256³ NIfTI", need: "img" },
{ act: saveScene, title: "Scene", sub: "everything, as a .nvd document", need: "img" },
];