-
-
Notifications
You must be signed in to change notification settings - Fork 420
Expand file tree
/
Copy pathindex.js
More file actions
1885 lines (1677 loc) · 66.7 KB
/
Copy pathindex.js
File metadata and controls
1885 lines (1677 loc) · 66.7 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 * as macro from 'vtk.js/Sources/macros';
import DeepEqual from 'fast-deep-equal';
import { vec3, mat3, mat4 } from 'gl-matrix';
import vtkBoundingBox from 'vtk.js/Sources/Common/DataModel/BoundingBox';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';
import { VtkDataTypes } from 'vtk.js/Sources/Common/Core/DataArray/Constants';
import vtkHelper from 'vtk.js/Sources/Rendering/OpenGL/Helper';
import vtkOpenGLFramebuffer from 'vtk.js/Sources/Rendering/OpenGL/Framebuffer';
import vtkOpenGLTexture from 'vtk.js/Sources/Rendering/OpenGL/Texture';
import vtkReplacementShaderMapper from 'vtk.js/Sources/Rendering/OpenGL/ReplacementShaderMapper';
import vtkShaderProgram from 'vtk.js/Sources/Rendering/OpenGL/ShaderProgram';
import vtkVertexArrayObject from 'vtk.js/Sources/Rendering/OpenGL/VertexArrayObject';
import vtkViewNode from 'vtk.js/Sources/Rendering/SceneGraph/ViewNode';
import { Representation } from 'vtk.js/Sources/Rendering/Core/Property/Constants';
import {
Wrap,
Filter,
} from 'vtk.js/Sources/Rendering/OpenGL/Texture/Constants';
import {
InterpolationType,
OpacityMode,
ColorMixPreset,
} from 'vtk.js/Sources/Rendering/Core/VolumeProperty/Constants';
import { BlendMode } from 'vtk.js/Sources/Rendering/Core/VolumeMapper/Constants';
import {
getTransferFunctionsHash,
getImageDataHash,
} from 'vtk.js/Sources/Rendering/OpenGL/RenderWindow/resourceSharingHelper';
import vtkVolumeVS from 'vtk.js/Sources/Rendering/OpenGL/glsl/vtkVolumeVS.glsl';
import vtkVolumeFS from 'vtk.js/Sources/Rendering/OpenGL/glsl/vtkVolumeFS.glsl';
import { registerOverride } from 'vtk.js/Sources/Rendering/OpenGL/ViewNodeFactory';
const { vtkWarningMacro, vtkErrorMacro } = macro;
// ----------------------------------------------------------------------------
// helper methods
// ----------------------------------------------------------------------------
// Some matrices to avoid reallocations when we need them
const preAllocatedMatrices = {
idxToView: mat4.identity(new Float64Array(16)),
vecISToVCMatrix: mat3.identity(new Float64Array(9)),
modelToView: mat4.identity(new Float64Array(16)),
projectionToView: mat4.identity(new Float64Array(16)),
projectionToWorld: mat4.identity(new Float64Array(16)),
};
// ----------------------------------------------------------------------------
// vtkOpenGLVolumeMapper methods
// ----------------------------------------------------------------------------
function vtkOpenGLVolumeMapper(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkOpenGLVolumeMapper');
function getUseIndependentComponents(actorProperty, numComp) {
const iComps = actorProperty.getIndependentComponents();
const colorMixPreset = actorProperty.getColorMixPreset();
return (iComps && numComp >= 2) || !!colorMixPreset;
}
function isLabelmapOutlineRequired(actorProperty) {
return (
actorProperty.getUseLabelOutline() ||
model.renderable.getBlendMode() ===
BlendMode.LABELMAP_EDGE_PROJECTION_BLEND
);
}
// Associate a reference counter to each graphics resource
const graphicsResourceReferenceCount = new Map();
function decreaseGraphicsResourceCount(openGLRenderWindow, coreObject) {
if (!coreObject) {
return;
}
const oldCount = graphicsResourceReferenceCount.get(coreObject) ?? 0;
const newCount = oldCount - 1;
if (newCount <= 0) {
openGLRenderWindow.unregisterGraphicsResourceUser(coreObject, publicAPI);
graphicsResourceReferenceCount.delete(coreObject);
} else {
graphicsResourceReferenceCount.set(coreObject, newCount);
}
}
function increaseGraphicsResourceCount(openGLRenderWindow, coreObject) {
if (!coreObject) {
return;
}
const oldCount = graphicsResourceReferenceCount.get(coreObject) ?? 0;
const newCount = oldCount + 1;
graphicsResourceReferenceCount.set(coreObject, newCount);
if (oldCount <= 0) {
openGLRenderWindow.registerGraphicsResourceUser(coreObject, publicAPI);
}
}
function replaceGraphicsResource(
openGLRenderWindow,
oldResourceCoreObject,
newResourceCoreObject
) {
if (oldResourceCoreObject === newResourceCoreObject) {
return;
}
decreaseGraphicsResourceCount(openGLRenderWindow, oldResourceCoreObject);
increaseGraphicsResourceCount(openGLRenderWindow, newResourceCoreObject);
}
function unregisterGraphicsResources(renderWindow) {
// Convert to an array using the spread operator as Firefox doesn't support Iterator.forEach()
[...graphicsResourceReferenceCount.keys()].forEach((coreObject) =>
renderWindow.unregisterGraphicsResourceUser(coreObject, publicAPI)
);
}
publicAPI.buildPass = () => {
model.zBufferTexture = null;
};
// ohh someone is doing a zbuffer pass, use that for
// intermixed volume rendering
publicAPI.zBufferPass = (prepass, renderPass) => {
if (prepass) {
const zbt = renderPass.getZBufferTexture();
if (zbt !== model.zBufferTexture) {
model.zBufferTexture = zbt;
}
}
};
publicAPI.opaqueZBufferPass = (prepass, renderPass) =>
publicAPI.zBufferPass(prepass, renderPass);
// Renders myself
publicAPI.volumePass = (prepass, renderPass) => {
if (prepass) {
const oldOglRenderWindow = model._openGLRenderWindow;
model._openGLRenderWindow = publicAPI.getLastAncestorOfType(
'vtkOpenGLRenderWindow'
);
if (
oldOglRenderWindow &&
!oldOglRenderWindow.isDeleted() &&
oldOglRenderWindow !== model._openGLRenderWindow
) {
// Unregister the mapper when the render window changes
unregisterGraphicsResources(oldOglRenderWindow);
}
model.context = model._openGLRenderWindow.getContext();
model.tris.setOpenGLRenderWindow(model._openGLRenderWindow);
model.jitterTexture.setOpenGLRenderWindow(model._openGLRenderWindow);
model.framebuffer.setOpenGLRenderWindow(model._openGLRenderWindow);
model.openGLVolume = publicAPI.getFirstAncestorOfType('vtkOpenGLVolume');
const actor = model.openGLVolume.getRenderable();
model._openGLRenderer =
publicAPI.getFirstAncestorOfType('vtkOpenGLRenderer');
const ren = model._openGLRenderer.getRenderable();
model.openGLCamera = model._openGLRenderer.getViewNodeFor(
ren.getActiveCamera(),
model.openGLCamera
);
publicAPI.renderPiece(ren, actor);
}
};
publicAPI.getShaderTemplate = (shaders, ren, actor) => {
shaders.Vertex = vtkVolumeVS;
shaders.Fragment = vtkVolumeFS;
shaders.Geometry = '';
};
publicAPI.replaceShaderValues = (shaders, ren, actor) => {
let FSSource = shaders.Fragment;
FSSource = vtkShaderProgram.substitute(
FSSource,
'//VTK::EnabledColorFunctions',
`#define EnableColorForValueFunctionId${model.previousState.colorForValueFunctionId}`
).result;
const enabledLightings = [];
if (model.previousState.surfaceLightingEnabled) {
enabledLightings.push('Surface');
}
if (model.previousState.volumeLightingEnabled) {
enabledLightings.push('Volume');
}
FSSource = vtkShaderProgram.substitute(
FSSource,
'//VTK::EnabledLightings',
enabledLightings.map(
(lightingType) => `#define Enable${lightingType}Lighting`
)
).result;
if (model.previousState.multiTexturePerVolumeEnabled) {
FSSource = vtkShaderProgram.substitute(
FSSource,
'//VTK::EnabledMultiTexturePerVolume',
'#define EnabledMultiTexturePerVolume'
).result;
}
if (model.previousState.useIndependentComponents) {
FSSource = vtkShaderProgram.substitute(
FSSource,
'//VTK::EnabledIndependentComponents',
'#define EnabledIndependentComponents'
).result;
}
if (model.previousState.gradientOpacityEnabled) {
FSSource = vtkShaderProgram.substitute(
FSSource,
'//VTK::EnabledGradientOpacity',
'#define EnabledGradientOpacity'
).result;
}
FSSource = vtkShaderProgram.substitute(
FSSource,
'//VTK::vtkProportionalComponents',
model.previousState.proportionalComponents
.map((component) => `#define vtkComponent${component}Proportional`)
.join('\n')
).result;
FSSource = vtkShaderProgram.substitute(
FSSource,
'//VTK::vtkForceNearestComponents',
model.previousState.forceNearestComponents
.map((component) => `#define vtkComponent${component}ForceNearest`)
.join('\n')
).result;
// if we have a ztexture then declare it and use it
if (model.previousState.hasZBufferTexture) {
FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::ZBuffer::Dec', [
'uniform sampler2D zBufferTexture;',
'uniform float vpZWidth;',
'uniform float vpZHeight;',
]).result;
FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::ZBuffer::Impl', [
'vec4 depthVec = texture2D(zBufferTexture, vec2(gl_FragCoord.x / vpZWidth, gl_FragCoord.y/vpZHeight));',
'float zdepth = (depthVec.r*256.0 + depthVec.g)/257.0;',
'zdepth = zdepth * 2.0 - 1.0;',
'if (cameraParallel == 0) {',
'zdepth = -2.0 * camFar * camNear / (zdepth*(camFar-camNear)-(camFar+camNear)) - camNear;}',
'else {',
'zdepth = (zdepth + 1.0) * 0.5 * (camFar - camNear);}\n',
'zdepth = -zdepth/rayDirVC.z;',
'dists.y = min(zdepth,dists.y);',
]).result;
}
// Set the BlendMode approach
FSSource = vtkShaderProgram.substitute(
FSSource,
'//VTK::BlendMode',
`${model.previousState.blendMode}`
).result;
FSSource = vtkShaderProgram.substitute(
FSSource,
'//VTK::NumberOfLights',
`${model.previousState.numberOfLights}`
).result;
FSSource = vtkShaderProgram.substitute(
FSSource,
'//VTK::MaxLaoKernelSize',
`${model.previousState.maxLaoKernelSize}`
).result;
FSSource = vtkShaderProgram.substitute(
FSSource,
'//VTK::NumberOfComponents',
`${model.previousState.numberOfComponents}`
).result;
FSSource = vtkShaderProgram.substitute(
FSSource,
'//VTK::MaximumNumberOfSamples',
`${model.previousState.maximumNumberOfSamples}`
).result;
shaders.Fragment = FSSource;
const numberOfClippingPlanes = model.previousState.numberOfClippingPlanes;
if (numberOfClippingPlanes > 0) {
FSSource = vtkShaderProgram.substitute(
FSSource,
'//VTK::ClipPlane::Dec',
[
`uniform vec3 vClipPlaneNormals[6];`,
`uniform float vClipPlaneDistances[6];`,
`uniform vec3 vClipPlaneOrigins[6];`,
`uniform int clip_numPlanes;`,
'//VTK::ClipPlane::Dec',
'#define vtkClippingPlanesOn',
],
false
).result;
FSSource = vtkShaderProgram.substitute(
FSSource,
'//VTK::ClipPlane::Impl',
[
`for(int i = 0; i < ${numberOfClippingPlanes}; i++) {`,
' float rayDirRatio = dot(rayDirVC, vClipPlaneNormals[i]);',
' float equationResult = dot(vertexVCVSOutput, vClipPlaneNormals[i]) + vClipPlaneDistances[i];',
' if (rayDirRatio == 0.0)',
' {',
' if (equationResult < 0.0) dists.x = dists.y;',
' continue;',
' }',
' float result = -1.0 * equationResult / rayDirRatio;',
' if (rayDirRatio < 0.0) dists.y = min(dists.y, result);',
' else dists.x = max(dists.x, result);',
'}',
'//VTK::ClipPlane::Impl',
],
false
).result;
}
shaders.Fragment = FSSource;
};
publicAPI.getNeedToRebuildShaders = (cellBO, ren, actor) => {
// These are all the variables that fully determine the behavior of replaceShaderValues
// and the exact content of the shader
// See replaceShaderValues method
const hasZBufferTexture = !!model.zBufferTexture;
const numberOfValidInputs = model.currentValidInputs.length;
const numberOfLights = model.numberOfLights;
const numberOfComponents = model.numberOfComponents;
const useIndependentComponents = model.useIndependentComponents;
// The volume property that is used is always the first one
const volumeProperties = actor.getProperties();
const firstValidInput = model.currentValidInputs[0];
const firstVolumeProperty = volumeProperties[firstValidInput.inputIndex];
// There are two modes:
// - single volume with multiple components
// - multiple volumes with one component per volume
const multiTexturePerVolumeEnabled = numberOfValidInputs > 1;
// Get maximum number of samples
const boundsMC = firstValidInput.imageData.getBounds();
const maximumRayLength = vtkBoundingBox.getDiagonalLength(boundsMC);
const maximumNumberOfSamples = Math.ceil(
maximumRayLength / publicAPI.getCurrentSampleDistance(ren)
);
if (maximumNumberOfSamples > model.renderable.getMaximumSamplesPerRay()) {
vtkWarningMacro(
`The number of steps required ${maximumNumberOfSamples} is larger than the ` +
`specified maximum number of steps ${model.renderable.getMaximumSamplesPerRay()}.\n` +
'Please either change the volumeMapper sampleDistance or its maximum number of samples.'
);
}
// Gradient opacity
const numberOfIndependantComponents = useIndependentComponents
? numberOfComponents
: 1;
let gradientOpacityEnabled = false;
for (let i = 0; i < numberOfIndependantComponents; ++i) {
if (firstVolumeProperty.getUseGradientOpacity(i)) {
gradientOpacityEnabled = true;
break;
}
}
// Get the max kernel size from volume properties that use LAO and
// that are linked to a valid input imageData
let maxLaoKernelSize = 0;
const kernelSize = firstVolumeProperty.getLAOKernelSize();
if (
kernelSize > maxLaoKernelSize &&
firstVolumeProperty.getLocalAmbientOcclusion() &&
firstVolumeProperty.getAmbient() > 0.0
) {
maxLaoKernelSize = kernelSize;
}
const numberOfClippingPlanes = model.renderable.getClippingPlanes().length;
// These are from the buildShader function in vtkReplacementShaderMapper
const mapperShaderReplacements =
model.renderable.getViewSpecificProperties().OpenGL?.ShaderReplacements;
const renderPassShaderReplacements =
model.currentRenderPass?.getShaderReplacement();
const blendMode = model.renderable.getBlendMode();
// This enables optimizing out some function which avoids huge shader compilation time
// The result of this computation is used in getColorForValue in the fragment shader
const colorForValueFunctionId = (() => {
// If labeloutline and not the edge labelmap, since in the edge labelmap blend
// we need the underlying data to sample through
if (
blendMode !== BlendMode.LABELMAP_EDGE_PROJECTION_BLEND &&
isLabelmapOutlineRequired(firstVolumeProperty)
) {
return 5;
}
if (useIndependentComponents) {
switch (firstVolumeProperty.getColorMixPreset()) {
case ColorMixPreset.ADDITIVE:
return 1;
case ColorMixPreset.COLORIZE:
return 2;
case ColorMixPreset.CUSTOM:
return 3;
default: // ColorMixPreset.DEFAULT
return 4;
}
}
return 0;
})();
// Get which types of lighting are enabled
const surfaceLightingEnabled =
firstVolumeProperty.getVolumetricScatteringBlending() < 1.0;
const volumeLightingEnabled =
firstVolumeProperty.getVolumetricScatteringBlending() > 0.0;
// Is any volume using ForceNearestInterpolation
let forceNearestInterpolationEnabled = false;
for (let component = 0; component < numberOfComponents; ++component) {
if (firstVolumeProperty.getForceNearestInterpolation(component)) {
forceNearestInterpolationEnabled = true;
break;
}
}
// Define any proportional components
const proportionalComponents = [];
const forceNearestComponents = [];
for (let component = 0; component < numberOfComponents; component++) {
if (
firstVolumeProperty.getOpacityMode(component) ===
OpacityMode.PROPORTIONAL
) {
proportionalComponents.push(component);
}
if (firstVolumeProperty.getForceNearestInterpolation(component)) {
forceNearestComponents.push(component);
}
}
const currentState = {
numberOfComponents,
useIndependentComponents,
proportionalComponents,
forceNearestComponents,
blendMode,
numberOfLights,
numberOfValidInputs,
maximumNumberOfSamples,
hasZBufferTexture,
maxLaoKernelSize,
numberOfClippingPlanes,
mapperShaderReplacements,
renderPassShaderReplacements,
colorForValueFunctionId,
surfaceLightingEnabled,
volumeLightingEnabled,
forceNearestInterpolationEnabled,
multiTexturePerVolumeEnabled,
gradientOpacityEnabled,
};
// We need to rebuild the shader if one of these variables has changed,
// since they are used in the shader template replacement step.
// We also need to rebuild if the shader source time is outdated.
if (
cellBO.getProgram()?.getHandle() === 0 ||
!model.previousState ||
!DeepEqual(model.previousState, currentState)
) {
model.previousState = currentState;
return true;
}
return false;
};
publicAPI.updateShaders = (cellBO, ren, actor) => {
// has something changed that would require us to recreate the shader?
if (publicAPI.getNeedToRebuildShaders(cellBO, ren, actor)) {
const shaders = { Vertex: null, Fragment: null, Geometry: null };
publicAPI.buildShaders(shaders, ren, actor);
// compile and bind the program if needed
const newShader = model._openGLRenderWindow
.getShaderCache()
.readyShaderProgramArray(
shaders.Vertex,
shaders.Fragment,
shaders.Geometry
);
// if the shader changed reinitialize the VAO
if (newShader !== cellBO.getProgram()) {
cellBO.setProgram(newShader);
// reset the VAO as the shader has changed
cellBO.getVAO().releaseGraphicsResources();
}
cellBO.getShaderSourceTime().modified();
} else {
model._openGLRenderWindow
.getShaderCache()
.readyShaderProgram(cellBO.getProgram());
}
cellBO.getVAO().bind();
publicAPI.setMapperShaderParameters(cellBO, ren, actor);
publicAPI.setCameraShaderParameters(cellBO, ren, actor);
publicAPI.setPropertyShaderParameters(cellBO, ren, actor);
publicAPI.getClippingPlaneShaderParameters(cellBO, ren, actor);
};
publicAPI.setMapperShaderParameters = (cellBO, ren, actor) => {
// Now to update the VAO too, if necessary.
const program = cellBO.getProgram();
if (
cellBO.getCABO().getElementCount() &&
(model.VBOBuildTime.getMTime() >
cellBO.getAttributeUpdateTime().getMTime() ||
cellBO.getShaderSourceTime().getMTime() >
cellBO.getAttributeUpdateTime().getMTime())
) {
if (program.isAttributeUsed('vertexDC')) {
if (
!cellBO
.getVAO()
.addAttributeArray(
program,
cellBO.getCABO(),
'vertexDC',
cellBO.getCABO().getVertexOffset(),
cellBO.getCABO().getStride(),
model.context.FLOAT,
3,
model.context.FALSE
)
) {
vtkErrorMacro('Error setting vertexDC in shader VAO.');
}
}
cellBO.getAttributeUpdateTime().modified();
}
const sampleDistance = publicAPI.getCurrentSampleDistance(ren);
program.setUniformf('sampleDistance', sampleDistance);
const volumeShadowSampleDistance =
sampleDistance * model.renderable.getVolumeShadowSamplingDistFactor();
program.setUniformf(
'volumeShadowSampleDistance',
volumeShadowSampleDistance
);
// Volume textures
model.scalarTextures.forEach((scalarTexture, component) => {
program.setUniformi(
`volumeTexture[${component}]`,
scalarTexture.getTextureUnit()
);
});
const volumeProperties = actor.getProperties();
const firstValidInput = model.currentValidInputs[0];
const firstVolumeProperty = volumeProperties[firstValidInput.inputIndex];
const ipScalarRange = firstVolumeProperty.getIpScalarRange();
const minVals = new Float32Array(4);
const maxVals = new Float32Array(4);
const setMinMaxVal = (component, volInfo, volInfoIndex) => {
// In some situations, we might not have computed the scale and offset
// for the data range, or it might not be needed.
if (volInfo?.dataComputedScale?.length) {
// convert iprange from 0-1 into data range values
minVals[component] =
ipScalarRange[0] * volInfo.dataComputedScale[volInfoIndex] +
volInfo.dataComputedOffset[volInfoIndex];
maxVals[component] =
ipScalarRange[1] * volInfo.dataComputedScale[volInfoIndex] +
volInfo.dataComputedOffset[volInfoIndex];
// convert data ranges into texture values
minVals[component] =
(minVals[component] - volInfo.offset[volInfoIndex]) /
volInfo.scale[volInfoIndex];
maxVals[component] =
(maxVals[component] - volInfo.offset[volInfoIndex]) /
volInfo.scale[volInfoIndex];
}
};
if (model.previousState.multiTexturePerVolumeEnabled) {
// Use the first component of all texture infos
model.scalarTextures.forEach((scalarTexture, component) => {
const volInfo = scalarTexture.getVolumeInfo();
setMinMaxVal(component, volInfo, 0);
});
} else {
// Use all components of the first texture info
const firstVolInfo = model.scalarTextures[0].getVolumeInfo();
for (let component = 0; component < 4; ++component) {
setMinMaxVal(component, firstVolInfo, component);
}
}
const uniformPrefix = 'volume';
program.setUniform4f(
`${uniformPrefix}.ipScalarRangeMin`,
minVals[0],
minVals[1],
minVals[2],
minVals[3]
);
program.setUniform4f(
`${uniformPrefix}.ipScalarRangeMax`,
maxVals[0],
maxVals[1],
maxVals[2],
maxVals[3]
);
// if we have a zbuffer texture then set it
if (model.zBufferTexture !== null) {
program.setUniformi(
'zBufferTexture',
model.zBufferTexture.getTextureUnit()
);
const size = model._useSmallViewport
? [model._smallViewportWidth, model._smallViewportHeight]
: model._openGLRenderWindow.getFramebufferSize();
program.setUniformf('vpZWidth', size[0]);
program.setUniformf('vpZHeight', size[1]);
}
};
publicAPI.setCameraShaderParameters = (cellBO, ren, actor) => {
// These matrices are not cached for their content, but only to avoid reallocations
const {
idxToView,
vecISToVCMatrix,
modelToView,
projectionToView,
projectionToWorld,
} = preAllocatedMatrices;
// [WMVP]C == {world, model, view, projection} coordinates
// E.g., WCPC == world to projection coordinate transformation
const keyMats = model.openGLCamera.getKeyMatrices(ren);
const actMats = model.openGLVolume.getKeyMatrices();
mat4.multiply(modelToView, keyMats.wcvc, actMats.mcwc);
const program = cellBO.getProgram();
const camera = model.openGLCamera.getRenderable();
const useParallelProjection = camera.getParallelProjection();
const clippingRange = camera.getClippingRange();
program.setUniformf('camThick', clippingRange[1] - clippingRange[0]);
program.setUniformf('camNear', clippingRange[0]);
program.setUniformf('camFar', clippingRange[1]);
program.setUniformi('cameraParallel', useParallelProjection);
// Compute the viewport bounds of the volume
// We will only render those fragments
// First, merge all bounds to get a fusion of all bounds in model coordinates
const firstValidInput = model.currentValidInputs[0];
const boundsMC = firstValidInput.imageData.getBounds();
const cornersMC = vtkBoundingBox.getCorners(boundsMC, []);
const cornersDC = cornersMC.map((corner) => {
// Convert to view coordinates
vec3.transformMat4(corner, corner, modelToView);
if (!useParallelProjection) {
// Now find the projection of this point onto a
// nearZ distance plane. Since pos is in view coordinates,
// scale it until pos.z == nearZ
const newScale = -clippingRange[0] / (corner[2] * vec3.length(corner));
vec3.scale(corner, corner, newScale);
}
// Now convert to display coordinates
vec3.transformMat4(corner, corner, keyMats.vcpc);
return corner;
});
const boundsDC = vtkBoundingBox.addPoints(
[...vtkBoundingBox.INIT_BOUNDS],
cornersDC
);
program.setUniformf('dcxmin', boundsDC[0]);
program.setUniformf('dcxmax', boundsDC[1]);
program.setUniformf('dcymin', boundsDC[2]);
program.setUniformf('dcymax', boundsDC[3]);
const size = publicAPI.getRenderTargetSize();
program.setUniformf('vpWidth', size[0]);
program.setUniformf('vpHeight', size[1]);
const offset = publicAPI.getRenderTargetOffset();
program.setUniformf('vpOffsetX', offset[0] / size[0]);
program.setUniformf('vpOffsetY', offset[1] / size[1]);
mat4.invert(projectionToView, keyMats.vcpc);
program.setUniformMatrix('PCVCMatrix', projectionToView);
program.setUniformi('twoSidedLighting', ren.getTwoSidedLighting());
const kernelSample = new Array(2 * model.previousState.maxLaoKernelSize);
for (let i = 0; i < model.previousState.maxLaoKernelSize; i++) {
kernelSample[i * 2] = Math.random();
kernelSample[i * 2 + 1] = Math.random();
}
program.setUniform2fv('kernelSample', kernelSample);
// Handle lighting values
if (model.numberOfLights > 0) {
let lightIndex = 0;
ren.getLights().forEach((light) => {
if (light.getSwitch() > 0) {
const lightPrefix = `lights[${lightIndex}]`;
// Merge color and intensity
const color = light.getColor();
const intensity = light.getIntensity();
const scaledColor = vec3.scale([], color, intensity);
program.setUniform3fv(`${lightPrefix}.color`, scaledColor);
// Position in view coordinates
const position = light.getTransformedPosition();
vec3.transformMat4(position, position, modelToView);
program.setUniform3fv(`${lightPrefix}.positionVC`, position);
// Convert lightDirection in view coordinates and normalize it
const direction = [...light.getDirection()];
vec3.transformMat3(direction, direction, keyMats.normalMatrix);
vec3.normalize(direction, direction);
program.setUniform3fv(`${lightPrefix}.directionVC`, direction);
// Camera direction of projection is (0, 0, -1.0) in view coordinates
const halfAngle = [
-0.5 * direction[0],
-0.5 * direction[1],
-0.5 * (direction[2] - 1.0),
];
program.setUniform3fv(`${lightPrefix}.halfAngleVC`, halfAngle);
// Attenuation
const attenuation = light.getAttenuationValues();
program.setUniform3fv(`${lightPrefix}.attenuation`, attenuation);
// Exponent
const exponent = light.getExponent();
program.setUniformf(`${lightPrefix}.exponent`, exponent);
// Cone angle
const coneAngle = light.getConeAngle();
program.setUniformf(`${lightPrefix}.coneAngle`, coneAngle);
// Positional flag
const isPositional = light.getPositional();
program.setUniformi(`${lightPrefix}.isPositional`, isPositional);
lightIndex++;
}
});
}
// Set uniforms for the volume
const uniformPrefix = 'volume';
const volumeProperties = actor.getProperties();
const firstVolumeProperty = volumeProperties[firstValidInput.inputIndex];
const firstImageData = firstValidInput.imageData;
const spatialExtent = firstImageData.getSpatialExtent();
const spacing = firstImageData.getSpacing();
const dimensions = firstImageData.getDimensions();
const idxToModel = firstImageData.getIndexToWorld();
const worldToIndex = firstImageData.getWorldToIndex();
const imageDirection = firstImageData.getDirectionByReference();
// idxToView is equivalent to applying idxToModel then modelToView
mat4.multiply(idxToView, modelToView, idxToModel);
// Set spacing uniform
program.setUniform3fv(`${uniformPrefix}.spacing`, spacing);
const inverseSpacing = vec3.inverse([], spacing);
program.setUniform3fv(`${uniformPrefix}.inverseSpacing`, inverseSpacing);
// Set dimensions uniform
program.setUniform3iv(`${uniformPrefix}.dimensions`, dimensions);
// Set inverse dimensions uniform
program.setUniform3fv(
`${uniformPrefix}.inverseDimensions`,
vec3.inverse([], dimensions)
);
// Set world to index
program.setUniformMatrix(`${uniformPrefix}.worldToIndex`, worldToIndex);
// Create the vecISToVCMatrix, that transform a point from texture coordinates (IS in the shader) to VC coordinates
vecISToVCMatrix.fill(0);
// First apply scaling
// mat3.fromScaling can't be used, because it uses a vec2 for scaling
const sizeVC = vec3.multiply(new Float64Array(3), dimensions, spacing);
vecISToVCMatrix[0] = sizeVC[0];
vecISToVCMatrix[4] = sizeVC[1];
vecISToVCMatrix[8] = sizeVC[2];
// Then apply the image direction matrix
mat3.multiply(vecISToVCMatrix, imageDirection, vecISToVCMatrix);
// Then apply the actor matrix
mat3.multiply(vecISToVCMatrix, actMats.normalMatrix, vecISToVCMatrix);
// Then apply the camera matrix
mat3.multiply(vecISToVCMatrix, keyMats.normalMatrix, vecISToVCMatrix);
program.setUniformMatrix3x3(
`${uniformPrefix}.vecISToVCMatrix`,
vecISToVCMatrix
);
program.setUniformMatrix3x3(
`${uniformPrefix}.vecVCToISMatrix`,
mat3.invert(new Float32Array(9), vecISToVCMatrix)
);
// Set originVC uniform that will be used to convert points from IS to VC
// It will be done in this way: posVC = vecISToVCMatrix * posIS + originVC
// Or the other way around: posIS = vecVCtoISMatrix * (posVC - originVC)
const spacialExtentMinIC = vec3.fromValues(
spatialExtent[0],
spatialExtent[2],
spatialExtent[4]
);
const originVC = vec3.transformMat4(
new Float64Array(3),
spacialExtentMinIC,
idxToView
);
program.setUniform3fv(`${uniformPrefix}.originVC`, originVC);
const diagonalLength = vec3.length(sizeVC);
program.setUniformf(`${uniformPrefix}.diagonalLength`, diagonalLength);
if (isLabelmapOutlineRequired(firstVolumeProperty)) {
const distance = camera.getDistance();
// set the clipping range to be model.distance and model.distance + 0.1
// since we use the in the keyMats.wcpc (world to projection) matrix
// the projection matrix calculation relies on the clipping range to be
// set correctly. This is done inside the interactorStyleMPRSlice which
// limits use cases where the interactor style is not used.
camera.setClippingRange(distance, distance + 0.1);
const labelOutlineKeyMats = model.openGLCamera.getKeyMatrices(ren);
// Get the projection coordinate to world coordinate transformation matrix.
mat4.invert(projectionToWorld, labelOutlineKeyMats.wcpc);
// reset the clipping range since the keyMats are cached
camera.setClippingRange(clippingRange[0], clippingRange[1]);
// to re compute the matrices for the current camera and cache them
model.openGLCamera.getKeyMatrices(ren);
program.setUniformMatrix(
`${uniformPrefix}.PCWCMatrix`,
projectionToWorld
);
}
if (firstVolumeProperty.getVolumetricScatteringBlending() > 0.0) {
program.setUniformf(
`${uniformPrefix}.globalIlluminationReach`,
firstVolumeProperty.getGlobalIlluminationReach()
);
program.setUniformf(
`${uniformPrefix}.volumetricScatteringBlending`,
firstVolumeProperty.getVolumetricScatteringBlending()
);
program.setUniformf(
`${uniformPrefix}.anisotropy`,
firstVolumeProperty.getAnisotropy()
);
program.setUniformf(
`${uniformPrefix}.anisotropySquared`,
firstVolumeProperty.getAnisotropy() ** 2.0
);
}
if (
firstVolumeProperty.getLocalAmbientOcclusion() &&
firstVolumeProperty.getAmbient() > 0.0
) {
const kernelSize = firstVolumeProperty.getLAOKernelSize();
program.setUniformi(`${uniformPrefix}.kernelSize`, kernelSize);
const kernelRadius = firstVolumeProperty.getLAOKernelRadius();
program.setUniformi(`${uniformPrefix}.kernelRadius`, kernelRadius);
} else {
program.setUniformi(`${uniformPrefix}.kernelSize`, 0);
}
};
publicAPI.setPropertyShaderParameters = (cellBO, ren, actor) => {
const program = cellBO.getProgram();
program.setUniformi('jtexture', model.jitterTexture.getTextureUnit());
const volumeProperties = actor.getProperties();
// There is only one label outline thickness texture
program.setUniformi(
`labelOutlineThicknessTexture`,
model.labelOutlineThicknessTexture.getTextureUnit()
);
program.setUniformi(
'opacityTexture',
model.opacityTexture.getTextureUnit()
);
program.setUniformi('colorTexture', model.colorTexture.getTextureUnit());
const uniformPrefix = 'volume';
const firstValidInput = model.currentValidInputs[0];
const firstVolumeProperty = volumeProperties[firstValidInput.inputIndex];
const numberOfComponents = model.previousState.numberOfComponents;
const useIndependentComponents =
model.previousState.useIndependentComponents;
// set the component mix when independent
if (useIndependentComponents) {
const independentComponentMix = new Float32Array(4);
for (let i = 0; i < numberOfComponents; i++) {
independentComponentMix[i] = firstVolumeProperty.getComponentWeight(i);
}
program.setUniform4fv(
`${uniformPrefix}.independentComponentMix`,
independentComponentMix
);
const transferFunctionsSampleHeight = new Float32Array(4);
const pixelHeight = 1 / numberOfComponents;
for (let i = 0; i < numberOfComponents; ++i) {
transferFunctionsSampleHeight[i] = (i + 0.5) * pixelHeight;
}
program.setUniform4fv(
`${uniformPrefix}.transferFunctionsSampleHeight`,
transferFunctionsSampleHeight
);
}
const colorForValueFunctionId = model.colorForValueFunctionId;
program.setUniformi(
`${uniformPrefix}.colorForValueFunctionId`,
colorForValueFunctionId
);
const computeNormalFromOpacity =
firstVolumeProperty.getComputeNormalFromOpacity();
program.setUniformi(
`${uniformPrefix}.computeNormalFromOpacity`,
computeNormalFromOpacity
);
// three levels of shift scale combined into one
// for performance in the fragment shader
const colorTextureScale = new Float32Array(4);
const colorTextureShift = new Float32Array(4);
const opacityTextureScale = new Float32Array(4);
const opacityTextureShift = new Float32Array(4);
for (let component = 0; component < numberOfComponents; component++) {
const useMultiTexture = model.previousState.multiTexturePerVolumeEnabled;
const textureIndex = useMultiTexture ? component : 0;
const volInfoIndex = useMultiTexture ? 0 : component;
const scalarTexture = model.scalarTextures[textureIndex];
const volInfo = scalarTexture.getVolumeInfo();
const target = useIndependentComponents ? component : 0;
const sscale = volInfo.scale[volInfoIndex];
// Color
const colorFunction = firstVolumeProperty.getRGBTransferFunction(target);
const colorRange = colorFunction.getRange();
colorTextureScale[component] = sscale / (colorRange[1] - colorRange[0]);
colorTextureShift[component] =
(volInfo.offset[volInfoIndex] - colorRange[0]) /
(colorRange[1] - colorRange[0]);
// Opacity
const opacityFunction = firstVolumeProperty.getScalarOpacity(target);
const opacityRange = opacityFunction.getRange();
opacityTextureScale[component] =
sscale / (opacityRange[1] - opacityRange[0]);