-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.html
executable file
·823 lines (783 loc) · 27.1 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<title>MRIcroGL for Web</title>
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
html,
body {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
background: #808080;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
li {
float: left;
}
li a,
.dropbtn {
/* menu header */
display: inline-block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover,
.dropdown:hover .dropbtn {
background-color: #44ABDA;
}
li.dropdown {
display: inline-block;
font-family: Arial, Helvetica, sans-serif;
}
.dropdown-content {
font-family: Arial, Helvetica, sans-serif;
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
}
.dropdown-content a {
/* menu items */
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
}
.dropdown-content a:hover {
background-color: #f1f1f1
}
.dropdown:hover .dropdown-content {
display: block;
}
.divider,
.linker,
.dropdown-item-checked,
.overlay {
border-top: 1px solid grey;
}
canvas {
display: block; /* prevents scrollbar */
border: 0;
width: 100vw;
height: 90vh;
max-width:100%;
max-height:100%;
overflow-x:hidden;
overflow-y:hidden;
top: 0;
left: 0;
margin: 0 auto;
}
<!--.dropdown-item-checked::before {
position: absolute;
left: .2rem;
content: '✓';
font-weight: 600;
}-->
</style>
</head>
<body>
<div id="menu-container">
<input id="file-input" type="file" name="name" style="display: none;" />
<ul>
<li class="dropdown">
<a href="javascript:void(0)" class="dropbtn" id="FileMenu">File</a>
<div class="dropdown-content">
<a class="viewBtn" id="Open">Open</a>
<a class="viewBtn" id="SaveBitmap">Screen Shot</a>
<a class="linker" href="https://github.com/rordenlab/MRIcroWeb">About</a>
</div>
</li>
<li class="dropdown">
<a href="javascript:void(0)" class="dropbtn" id="ViewMenu">View</a>
<div class="dropdown-content">
<a class="viewBtn" id="L">Left</a>
<a class="viewBtn" id="R">Right</a>
<a class="viewBtn" id="P">Posterior</a>
<a class="viewBtn" id="A">Anterior</a>
<a class="viewBtn" id="I">Inferior</a>
<a class="viewBtn" id="S">Superior</a>
</div>
</li>
<li class="dropdown">
<a href="javascript:void(0)" class="dropbtn">Color</a>
<div class="dropdown-content">
<a class="viewBtn" id="!Gray">Gray</a>
<a class="viewBtn" id="!Plasma">Plasma</a>
<a class="viewBtn" id="!Viridis">Viridis</a>
<a class="viewBtn" id="!Inferno">Inferno</a>
<!-- <a class="viewBtn dropdown-item-checked" id="^Lighting">Lighting</a> -->
<a class="divider" id="BackColor">Background Color</a>
<a class="viewBtn" id="ChangeContrast">Adjust brightness and contrast</a>
<a class="viewBtn" id="OpacityInc">Harder Edges</a>
<a class="viewBtn" id="OpacityDec">Softer Edges</a>
</div>
</li>
<li class="dropdown">
<a href="javascript:void(0)" class="dropbtn">Shader</a>
<div class="dropdown-content">
<a class="viewBtn" id="^Standard">Standard</a>
<a class="viewBtn" id="^Lighting">Lighting</a>
<a class="viewBtn" id="^MIP">Maximum Intensity</a>
<a class="viewBtn" id="^Gradients">Gradients</a>
</div>
</li>
<li class="dropdown">
<a href="javascript:void(0)" class="dropbtn">Examples</a>
<div class="dropdown-content">
<a class="viewBtn" id="_spm152.nii.gz">spm</a>
<a class="viewBtn" id="_avg152T1_LR_nifti.nii.gz">avg</a>
<a class="viewBtn" id="_Chris_MRA.nii.gz">MRA</a>
<a class="viewBtn" id="_Chris_T1.nii.gz">T1</a>
<a class="viewBtn" id="_Chris_T2.nii.gz">T2</a>
</div>
</li>
</ul>
</div>
<div id="gl-container" ondrop="drop(event)" ondragover="allowDrop(event)">
<canvas id="glcanvas"></canvas>
</div>
</body>
<script src="nifti/nifti-reader.js"></script>
<script src="volume/gl-matrix-min.js"></script>
<script src="volume/webgl-util.js"></script>
<script src="volume/shader-srcs.js"></script>
<script src="volume/FileSaver.js"></script>
<script>
//https://stackoverflow.com/questions/21286887/adding-check-marks-to-bootstrap-button-drop-down-items
//var cubeStrip = [1,1,0, 0,1,0, 1,1,1, 0,1,1, 0,0,1, 0,1,0, 0,0,0, 1,1,0, 1,0,0, 1,1,1, 1,0,1, 0,0,1, 1,0,0, 0,0,0];
var takeScreenShot = false;
var cubeStrip = [0,1,0, 1,1,0, 0,1,1, 1,1,1, 1,0,1, 1,1,0, 1,0,0, 0,1,0, 0,0,0, 0,1,1, 0,0,1, 1,0,1, 0,0,0, 1,0,0];
var container = null;
var isBlackBackColor = true;
var gl = null;
var isDrawOnDemand = true;
var canvas = null;
var shader = null;
var blurShader = null;
var sobelShader = null;
var volumeTexture = null;
var gradientTexture = null;
var colormap = null;
var proj = null;
var vao = null;
var vbo = null;
//var tex = null;
var camera = null;
var projView = null;
var newVolumeUpload = true;
var targetFrameTime = 32;
var samplingRate = 1.0;
var WIDTH = 320;
var HEIGHT = 320;
canvas = document.getElementById("glcanvas");
var hdr;
var img;
var colorName = "";
var colorOpacity = 2;
const center = vec3.set(vec3.create(), 0.5, 0.5, 0.5);
var openDialog = document.createElement('input');
openDialog.type = 'file';
openDialog.onchange = e => {
selectVolume(e.target.files[0], false);
}
document.addEventListener("keydown", function(evt) {
if (evt.key == "z") adjustOpacity(0.9);
if (evt.key == "a") adjustOpacity(1.1);
if (evt.key == "w") adjustQuality(1.1);
if (evt.key == "q") adjustQuality(0.9);
});
if (isDrawOnDemand)
document.addEventListener('cameraRedraw', e => glDraw() );
function adjustQuality(scale) {
samplingRate = samplingRate * scale;
samplingRate = Math.min(samplingRate, 10.0);
samplingRate = Math.max(samplingRate, 0.7);
gl.uniform1f(shader.uniforms["dt_scale"], samplingRate);
console.log('quality ', samplingRate);
if (isDrawOnDemand) glDraw();
}
function adjustOpacity(scale) {
colorOpacity = colorOpacity * scale;
colorOpacity = Math.min(colorOpacity, 10.0);
colorOpacity = Math.max(colorOpacity, 0.1);
selectColormap(colorName);
console.log('opacity ', colorOpacity);
if (isDrawOnDemand) glDraw();
}
var loadVolume = function(url, isURL, onload) {
if (!isURL) {
var reader = new FileReader();
reader.readAsArrayBuffer(url);
reader.addEventListener('load', function(event) {
console.log(event.target.result);
//loadGeometryCore(object, isOverlay);
var hdr = nifti.readHeader(event.target.result);
var img;
if (nifti.isCompressed(event.target.result)) {
img = nifti.readImage(hdr, nifti.decompress(event.target.result));
} else
img = nifti.readImage(hdr, event.target.result);
//img = new Uint8Array(img);
onload(url, hdr, img);
});
return;
}
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.responseType = "arraybuffer";
req.onprogress = function(evt) {
//loadingProgressBar.setAttribute("style", "width: " + percent.toFixed(2) + "%");
};
req.onerror = function(evt) {
console.log = "Error Loading Volume";
};
req.onload = function(evt) {
var dataBuffer = req.response;
if (dataBuffer) {
var hdr = nifti.readHeader(dataBuffer);
var img;
if (nifti.isCompressed(dataBuffer)) {
img = nifti.readImage(hdr, nifti.decompress(dataBuffer));
} else
img = nifti.readImage(hdr, dataBuffer);
//img = new Uint8Array(img);
onload(url, hdr, img);
} else {
alert("Unable to load buffer properly from volume?");
console.log("no buffer?");
}
};
req.send();
} //loadVolume()
function bindBlankGL() {
let texR = gl.createTexture();
gl.bindTexture(gl.TEXTURE_3D, texR);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_R, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.pixelStorei( gl.UNPACK_ALIGNMENT, 1 )
gl.texStorage3D(gl.TEXTURE_3D, 1, gl.RGBA8, hdr.dims[1], hdr.dims[2], hdr.dims[3]);
return texR;
}
function gradientGL() {
var faceStrip = [0,0,0, 0,1,0, 1,0,0, 1,1,0];
var vao2 = gl.createVertexArray();
gl.bindVertexArray(vao2);
vbo2 = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vbo2);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(faceStrip), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);
var fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.disable(gl.CULL_FACE);
gl.viewport(0, 0, hdr.dims[1], hdr.dims[2]);
gl.disable(gl.BLEND);
tempTex3D = bindBlankGL();
blurShader.use();
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_3D, tex);
gl.uniform1i(blurShader.uniforms["intensityVol"], 1);
gl.uniform1f(blurShader.uniforms["dX"], 0.7/ hdr.dims[1]);
gl.uniform1f(blurShader.uniforms["dY"], 0.7/ hdr.dims[2]);
gl.uniform1f(blurShader.uniforms["dZ"], 0.7/ hdr.dims[3]);
gl.bindVertexArray(vao2);
for (i = 0; i < (hdr.dims[3]-1); i++) {
var coordZ = 1/hdr.dims[3] * (i + 0.5);
gl.uniform1f(blurShader.uniforms["coordZ"], coordZ);
gl.framebufferTextureLayer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, tempTex3D, 0, i);
gl.clear(gl.DEPTH_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, faceStrip.length / 3);
}
sobelShader.use();
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_3D, tempTex3D);//input texture
gl.uniform1i(sobelShader.uniforms["intensityVol"], 1);
gl.uniform1f(sobelShader.uniforms["dX"], 0.7/ hdr.dims[1]);
gl.uniform1f(sobelShader.uniforms["dY"], 0.7/ hdr.dims[2]);
gl.uniform1f(sobelShader.uniforms["dZ"], 0.7/ hdr.dims[3]);
gl.uniform1f(sobelShader.uniforms["coordZ"], 0.5);
gl.bindVertexArray(vao2);
gl.activeTexture(gl.TEXTURE0);
if (gradientTexture !== null) gl.deleteTexture(gradientTexture);
gradientTexture = bindBlankGL();
for (i = 0; i < (hdr.dims[3]-1); i++) {
var coordZ = 1/hdr.dims[3] * (i + 0.5);
gl.uniform1f(sobelShader.uniforms["coordZ"], coordZ);
//console.log(coordZ);
gl.framebufferTextureLayer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gradientTexture, 0, i);
gl.clear(gl.DEPTH_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, faceStrip.length / 3);
}
gl.deleteFramebuffer(fb);
gl.deleteTexture(tempTex3D);
//return to volume rendering shader
shader.use();
gl.bindVertexArray(vao);
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_3D, volumeTexture);
gl.activeTexture(gl.TEXTURE2);
gl.bindTexture(gl.TEXTURE_3D, gradientTexture);
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
}
function reportMat(m){
console.log("m = [%.2f %.2f %.2f %.2f; %.2f %.2f %.2f %.2f; %.2f %.2f %.2f %.2f; %.2f %.2f %.2f %.2f]",
m[0],m[1],m[2],m[3],
m[4],m[5],m[6],m[7],
m[8],m[9],m[10],m[11],
m[12],m[13],m[14],m[15],
);
}
function glDraw(){
gl.uniform1f(shader.uniforms["dt_scale"], samplingRate);
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.clear(gl.COLOR_BUFFER_BIT);
projView = mat4.mul(projView, proj, camera.camera);
gl.uniformMatrix4fv(shader.uniforms["proj_view"], false, projView);
//var eye = [camera.invCamera[12], camera.invCamera[13], camera.invCamera[14]];
var eye = camera.eyePos();
gl.uniform3fv(shader.uniforms["eye_pos"], eye);
//Lighting
//"Head-light" with light at camera location:
//gl.uniform3fv(shader.uniforms["light_pos"], eye);
//we will place a light directly above the camera, mixing headlight with top light
var mx = Math.max( Math.abs(...eye) );
up = camera.upDir();
var light = eye;
light[0] = eye[0] + up[0] * mx;
light[1] = eye[1] + up[1] * mx;
light[2] = eye[2] + up[2] * mx;
gl.uniform3fv(shader.uniforms["light_pos"], light);
//draw cube
gl.drawArrays(gl.TRIANGLE_STRIP, 0, cubeStrip.length / 3);
// Wait for rendering to actually finish
gl.finish();
if (takeScreenShot) {
takeScreenShot = false;
canvas.toBlob(function(b) { saveAs(b, "screen.png"); }, "image/png");
}
}
function updateVolume() { //load volume or change contrast
//convert data to 8-bit image
vox = hdr.dims[1] * hdr.dims[2] * hdr.dims[3];
img8 = new Uint8Array(vox);
if (hdr.datatypeCode === 2) //data already uint8
imgRaw = new Uint8Array(img);
else if (hdr.datatypeCode === 4)
var imgRaw = new Int16Array(img);
else if (hdr.datatypeCode === 16)
var imgRaw = new Float32Array(img);
else if (hdr.datatypeCode === 512)
var imgRaw = new Uint16Array(img);
mn = hdr.cal_min;
mx = hdr.cal_max;
var scale = 1;
if (mx > mn) scale = 255 / (mx-mn);
for (i = 0; i < (vox-1); i++) {
v = imgRaw[i];
v = (v * hdr.scl_slope) + hdr.scl_inter;
if (v < mn)
img8[i] = 0;
else if (v > mx)
img8[i] = 255;
else
img8[i] = (v-mn) * scale;
}
tex = gl.createTexture();
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_3D, tex);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_R, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.pixelStorei( gl.UNPACK_ALIGNMENT, 1 )
gl.texStorage3D(gl.TEXTURE_3D, 1, gl.R8, hdr.dims[1], hdr.dims[2], hdr.dims[3]);
gl.texSubImage3D(gl.TEXTURE_3D, 0, 0, 0, 0,hdr.dims[1], hdr.dims[2], hdr.dims[3],gl.RED, gl.UNSIGNED_BYTE, img8);
var longestAxis = Math.max(hdr.dims[1], Math.max(hdr.dims[2], hdr.dims[3]));
var volScale = [hdr.dims[1] / longestAxis, hdr.dims[2] / longestAxis,hdr.dims[3] / longestAxis];
gl.uniform3iv(shader.uniforms["volume_dims"], [hdr.dims[1],hdr.dims[2],hdr.dims[3]]);
gl.uniform3fv(shader.uniforms["volume_scale"], volScale);
newVolumeUpload = true;
//gradientGL();
if (!volumeTexture) {
volumeTexture = tex;
if (isDrawOnDemand)
;//glDraw();
else {
setInterval(function() {
// Save them some battery if they're not viewing the tab
if (document.hidden) {
return;
}
var startTime = new Date();
// Reset the sampling rate and camera for new volumes
if (newVolumeUpload) {
onWindowResize();
samplingRate = 1.0;
gl.uniform1f(shader.uniforms["dt_scale"], samplingRate);
}
glDraw();
var endTime = new Date();
var renderTime = endTime - startTime;
var targetSamplingRate = renderTime / targetFrameTime;
if (takeScreenShot) {
takeScreenShot = false;
canvas.toBlob(function(b) { saveAs(b, "screen.png"); }, "image/png");
}
// If we're dropping frames, decrease the sampling rate
if (!newVolumeUpload && targetSamplingRate > samplingRate) {
samplingRate = 0.8 * samplingRate + 0.2 * targetSamplingRate;
gl.uniform1f(shader.uniforms["dt_scale"], samplingRate);
}
newVolumeUpload = false;
startTime = endTime;
}, targetFrameTime);
}
} else {
gl.deleteTexture(volumeTexture);
volumeTexture = tex;
if (isDrawOnDemand) glDraw();
}
gradientGL();
glDraw();
} //updateVolume()
var selectVolume = function(url, isURL = true) {
loadVolume(url, isURL, function(file, xhdr, ximg) {
hdr = xhdr;
img = ximg;
//determine range
var imgRaw;
if (hdr.datatypeCode === 2) //data already uint8
imgRaw = new Uint8Array(img);
else if (hdr.datatypeCode === 4) //Int16
imgRaw = new Int16Array(img);
else if (hdr.datatypeCode === 16) //Float32
imgRaw = new Float32Array(img);
else if (hdr.datatypeCode === 512) //UInt16
imgRaw = new Uint16Array(img);
else {
alert('Unsupported data type');
console.log("Unsupported data type %d", hdr.datatypeCode);
var e = new Error('Unsupported data type', hdr.datatypeCode);
throw e;
}
var vox = imgRaw.length;
var mn = Infinity;
var mx = -Infinity;
for (i = 0; i < (vox-1); i++) {
if (!isFinite(imgRaw[i])) continue;
if (imgRaw[i] < mn) mn = imgRaw[i];
if (imgRaw[i] > mx) mx = imgRaw[i];
}
//calibrate intensity
if ((isFinite(hdr.scl_slope)) && (isFinite(hdr.scl_inter)) && (hdr.scl_slope !== 0.0 )) {
//console.log(">> mn %f mx %f %f %f", mn, mx, hdr.scl_slope, hdr.scl_inter);
mn = (mn * hdr.scl_slope) + hdr.scl_inter;
mx = (mx * hdr.scl_slope) + hdr.scl_inter;
} else {
hdr.scl_slope = 1.0;
hdr.scl_inter = 0.0;
}
//console.log("vx %d type %d mn %f mx %f", vox, hdr.datatypeCode, mn, mx);
//console.log("cal mn..mx %f..%f", hdr.cal_min, hdr.cal_max);
hdr.global_min = mn;
hdr.global_max = mx;
if ((!isFinite(hdr.cal_min)) || (!isFinite(hdr.cal_max)) || (hdr.cal_min >= hdr.cal_max)) {
hdr.cal_min = mn;
hdr.cal_max = mx;
}
updateVolume();
});
} // selectVolume()
function textureFromPixelArray(gl, dataArray, type, width, height) {
var dataTypedArray = new Uint8Array(dataArray); // Don't need to do this if the data is already in a typed array
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, type, width, height, 0, type, gl.UNSIGNED_BYTE, dataTypedArray);
// Other texture setup here, like filter modes and mipmap generation
return texture;
} // textureFromPixelArray()
function makeLut(Rs, Gs, Bs, As, Is) {
//create color lookup table provided arrays of reds, greens, blues, alphas and intensity indices
//intensity indices should be in increasing order with the first value 0 and the last 255.
// makeLut([0, 255], [0, 0], [0,0], [0,128],[0,255]); //red gradient
var lut = new Uint8Array(256 * 4);
for (i = 0; i < (Is.length-1); i++) {
//return a + f * (b - a);
var idxLo = Is[i];
var idxHi = Is[i+1];
var idxRng = idxHi - idxLo;
var k = idxLo * 4;
for (j = idxLo; j <= idxHi; j++) {
var f = (j-idxLo)/idxRng;
lut[k] = Rs[i] + f * (Rs[i+1]- Rs[i]); //Red
k++;
lut[k] = Gs[i] + f * (Gs[i+1]- Gs[i]); //Green
k++;
lut[k] = Bs[i] + f * (Bs[i+1]- Bs[i]); //Blue
k++;
lut[k] = (As[i] + f * (As[i+1]- As[i])) * colorOpacity; //Alpha
k++;
}
}
return lut;
} // makeLut()
var selectColormap = function(lutName) {
var lut = makeLut([0, 255], [0, 255], [0,255], [0,128],[0,255]); //gray
if (lutName === "Plasma")
lut = makeLut([13, 156, 237, 240],[8, 23, 121, 249],[135, 158, 83, 33],[0, 56, 80, 88], [0, 64, 192, 255]); //plasma
if (lutName === "Viridis")
lut = makeLut([68,49,53,253],[1,104,183,231],[84,142,121,37],[0,56,80,88],[0,65,192,255]);//viridis
if (lutName === "Inferno")
lut = makeLut([0,120,237,240],[0,28,105,249],[4,109,37,33],[0,56,80,88],[0,64,192,255]);//inferno
colorName = lutName;
if (colormap !== null)
gl.deleteTexture(colormap); //release colormap');
colormap = gl.createTexture();
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, colormap);
gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, 256, 1);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_R, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 256, 1,gl.RGBA, gl.UNSIGNED_BYTE, lut);
} // selectColormap()
window.onload = function(){
//menu items
var buttons = document.getElementsByClassName("viewBtn");
for (let i = 0; i < buttons.length; i++)
buttons[i].addEventListener("click", onButtonClick, false);
buttons = document.getElementsByClassName("divider");
for (let i = 0; i < buttons.length; i++)
buttons[i].addEventListener("click", onButtonClick, false);
gl = canvas.getContext("webgl2");
if (!gl) {
alert("Unable to initialize WebGL2. Your browser may not support it");
return;
}
window.addEventListener('resize', onWindowResize, false);
onWindowResize(true);
// Register mouse and touch listeners
var controller = new Controller();
controller.mousemove = function(prev, cur, evt) {
if (evt.buttons == 1) {
camera.rotate(prev, cur);
} else if (evt.buttons == 2) {
camera.pan([cur[0] - prev[0], prev[1] - cur[1]]);
}
};
controller.wheel = function(amt) { camera.zoom(amt); };
controller.pinch = controller.wheel;
controller.twoFingerDrag = function(drag) { camera.pan(drag); };
controller.registerForCanvas(canvas);
// Setup VAO and VBO to render the cube to run the raymarching shader
vao = gl.createVertexArray();
gl.bindVertexArray(vao);
vbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(cubeStrip), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);
sobelShader = new Shader(blurVertShader, sobelFragShader);
sobelShader.use();
blurShader = new Shader(blurVertShader, blurFragShader);
blurShader.use();
setShader(1); //Lighting shader
// Setup required OpenGL state for drawing the back faces and
// composting with the background color
gl.enable(gl.CULL_FACE);
gl.cullFace(gl.FRONT);
gl.enable(gl.BLEND);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
//gl.clearColor(1, 0.5, 0.5, 3);
// Load the default colormap and upload it, after which we
// load the default volume.
selectColormap("Gray");
selectVolume("spmSmall.nii.gz");
} // window.onload()
function setShader(shaderInt) { //0=default, 1=lighting, 2=Maximum Intensity
if (shaderInt === 3)
shader = new Shader(vertShader, fragShaderGradients);
else if (shaderInt === 2)
shader = new Shader(vertShader, fragShaderMIP);
else if (shaderInt === 1)
shader = new Shader(vertShader, fragShaderLighting);
else
shader = new Shader(vertShader, fragShader);
shader.use();
gl.uniform1i(shader.uniforms["volume"], 0);
gl.uniform1i(shader.uniforms["colormap"], 1);
gl.uniform1i(shader.uniforms["gradients"], 2);
gl.uniform1f(shader.uniforms["dt_scale"], 1.0);
}
function onWindowResize(isInit = false) {
WIDTH = canvas.clientWidth;
HEIGHT = canvas.clientHeight;//menuHeight;
// Check if the canvas is not the same size.
if (canvas.width != WIDTH || canvas.height != HEIGHT) {
// Make the canvas the same size
canvas.width = WIDTH;
canvas.height = HEIGHT;
//console.log("<< %s %s", WIDTH, HEIGHT);
}
//https://webglfundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
proj = mat4.perspective(mat4.create(), 15 * Math.PI / 180.0,WIDTH / HEIGHT, 0.1, 100);
camera = new ArcballCamera(center, 2, [WIDTH, HEIGHT]);
projView = mat4.create();
const kRot = Math.sqrt(0.5);
camera.rotateY([0.0,kRot]);
camera.rotateY([kRot,0.0]);
//if (isInit) return;
//samplingRate = 1.0;
//gl.uniform1f(shader.uniforms["dt_scale"], samplingRate);
if ((shader !==null) && (isDrawOnDemand)) glDraw();
} //onWindowResize()
function onButtonClick(event) {
var el = this.parentNode;
el.style.display = "none";
setTimeout(function() { //close menu
el.style.removeProperty("display");
}, 500);
if (event.target.id === "ChangeContrast") {
str = prompt("Set display intensity minimum and maximum", hdr.cal_min.toString()+" "+hdr.cal_max.toString() );
//if (isNaN(n))
// return;
var strs = str.split(" ");
if (strs.length < 2) return;
hdr.cal_min = +strs[0];
hdr.cal_max = +strs[1];
updateVolume();
return;
}
if (event.target.id === "SaveBitmap") {
takeScreenShot = true;
if (isDrawOnDemand) glDraw();
return;
}
if(event.target.id.charAt(0) === '^') { //shader
s = event.target.id.substr(1);
console.log("Setting shader to "+ s);
if (s === "Lighting")
setShader(1);
else if (s === "MIP")
setShader(2);
else if (s === "Gradients")
setShader(3);
else
setShader(0);
updateVolume();
//this.toggleClass('dropdown-item-checked');
if (isDrawOnDemand) glDraw();
return;
}
if(event.target.id.charAt(0) === '!') { //load color scheme
s = event.target.id.substr(1);
colorOpacity = 2.0;
selectColormap(s);
if (isDrawOnDemand) glDraw();
return;
}
if(event.target.id.charAt(0) === '_') { //load NIfTI volume
s = event.target.id.substr(1);
selectVolume(s);
return;
}
if (event.target.id === "Open") {
openDialog.click();
return;
}
if (event.target.id === "About") {
alert("MRIcroGL for Web by Chris Rorden. Using Will Usher's Volume Raycaster");
return;
}
if (event.target.id === "OpacityInc") {
adjustOpacity(1.2);
return;
}
if (event.target.id === "OpacityDec") {
adjustOpacity(0.8);
return;
}
if (event.target.id === "BackColor") {
if (isBlackBackColor)
document.body.style.background = "#FFFFFF";
else
document.body.style.background = "#000000";
isBlackBackColor = !isBlackBackColor;
return;
}
const kRot = Math.sqrt(0.5);
if (event.target.id === "R") {
camera = new ArcballCamera(center, 2, [WIDTH, HEIGHT]);
camera.rotateY([0.0,kRot]);
camera.rotateY([-kRot,0.0]);
if (isDrawOnDemand) glDraw();
return;
}
if (event.target.id === "L") {
camera = new ArcballCamera(center, 2, [WIDTH, HEIGHT]);
camera.rotateY([0.0,kRot]);
camera.rotateY([kRot,0.0]);
if (isDrawOnDemand) glDraw();
return;
}
if (event.target.id === "A") {
camera = new ArcballCamera(center, 2, [WIDTH, HEIGHT]);
camera.rotateY([0.0,kRot]);
camera.rotateY([kRot*2,0.0]);
if (isDrawOnDemand) glDraw();
return;
}
if (event.target.id === "P") {
camera = new ArcballCamera(center, 2, [WIDTH, HEIGHT]);
camera.rotateY([0.0,kRot]);
if (isDrawOnDemand) glDraw();
return;
}
if (event.target.id === "I") {
camera = new ArcballCamera(center, 2, [WIDTH, HEIGHT]);
camera.rotateY([-2*kRot,0]);
if (isDrawOnDemand) glDraw();
return;
}
if (event.target.id === "S") {
camera = new ArcballCamera(center, 2, [WIDTH, HEIGHT]);
if (isDrawOnDemand) glDraw();
return;
}
console.log('Unknown menu item ', event.target.id);
} //onButtonClick()
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
console.log(ev.dataTransfer.files[0])
selectVolume(ev.dataTransfer.files[0], false);
}
</script>
</html>