File: vtkVolumeTexture.cxx

package info (click to toggle)
paraview 5.11.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 497,236 kB
  • sloc: cpp: 3,171,290; ansic: 1,315,072; python: 134,290; xml: 103,324; sql: 65,887; sh: 5,286; javascript: 4,901; yacc: 4,383; java: 3,977; perl: 2,363; lex: 1,909; f90: 1,255; objc: 143; makefile: 119; tcl: 59; pascal: 50; fortran: 29
file content (1234 lines) | stat: -rw-r--r-- 40,388 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
#include <algorithm>

#include "vtkBlockSortHelper.h"
#include "vtkCamera.h"
#include "vtkDataArray.h"
#include "vtkDataArrayRange.h"
#include "vtkFloatArray.h"
#include "vtkImageData.h"
#include "vtkMatrix3x3.h"
#include "vtkMatrix4x4.h"
#include "vtkNew.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenGLState.h"
#include "vtkRectilinearGrid.h"
#include "vtkRenderer.h"
#include "vtkTextureObject.h"
#include "vtkUniformGrid.h"
#include "vtkUnsignedCharArray.h"
#include "vtkVolumeProperty.h"
#include "vtkVolumeTexture.h"
#include "vtk_glew.h"

VTK_ABI_NAMESPACE_BEGIN
vtkVolumeTexture::vtkVolumeTexture()
  : HandleLargeDataTypes(false)
  , InterpolationType(vtkTextureObject::Linear)
  , Texture(nullptr)
  , CurrentBlockIdx(0)
  , StreamBlocks(false)
  , Scalars(nullptr)
{
  this->Partitions[0] = this->Partitions[1] = this->Partitions[2] = 1;

  this->ScalarRange[0][0] = this->ScalarRange[0][1] = 0.f;
  this->ScalarRange[1][0] = this->ScalarRange[1][1] = 0.f;
  this->ScalarRange[2][0] = this->ScalarRange[2][1] = 0.f;
  this->ScalarRange[3][0] = this->ScalarRange[3][1] = 0.f;

  this->Scale[0] = 1.0f;
  this->Bias[0] = 0.0f;
  this->Scale[1] = 1.0f;
  this->Bias[1] = 0.0f;
  this->Scale[2] = 1.0f;
  this->Bias[2] = 0.0f;
  this->Scale[3] = 1.0f;
  this->Bias[3] = 0.0f;

  this->CellToPointMatrix->Identity();
  this->AdjustedTexMin[0] = this->AdjustedTexMin[1] = this->AdjustedTexMin[2] = 0.0f;
  this->AdjustedTexMin[3] = 1.0f;
  this->AdjustedTexMax[0] = this->AdjustedTexMax[1] = this->AdjustedTexMax[2] = 1.0f;
  this->AdjustedTexMax[3] = 1.0f;
}

//------------------------------------------------------------------------------
vtkVolumeTexture::~vtkVolumeTexture()
{
  this->ClearBlocks();
}

//------------------------------------------------------------------------------
vtkStandardNewMacro(vtkVolumeTexture);

//------------------------------------------------------------------------------
bool vtkVolumeTexture::LoadVolume(vtkRenderer* ren, vtkDataSet* data, vtkDataArray* scalars,
  int const isCell, int const interpolation)
{
  this->ClearBlocks();
  this->Scalars = scalars;
  this->IsCellData = isCell;
  this->InterpolationType = interpolation;
  vtkImageData* imData = vtkImageData::SafeDownCast(data);
  vtkRectilinearGrid* rGrid = vtkRectilinearGrid::SafeDownCast(data);
  if (imData)
  {
    imData->GetExtent(this->FullExtent.GetData());
  }
  else if (rGrid)
  {
    rGrid->GetExtent(this->FullExtent.GetData());
  }

  // Setup partition blocks
  if (this->Partitions[0] > 1 || this->Partitions[1] > 1 || this->Partitions[2] > 1)
  {
    // TODO: Partitions are only supported for image data input for now.
    if (!imData)
    {

      vtkErrorMacro(<< "Partitioning only supported for vtkImageData input right now!");
      return false;
    }
    this->SplitVolume(imData, this->Partitions);
  }
  else // Single block
  {
    if (this->IsCellData == 1)
    {
      this->AdjustExtentForCell(this->FullExtent);
    }
    if (imData)
    {
      vtkImageData* singleBlock = nullptr;
      if (vtkUniformGrid* ugData = vtkUniformGrid::SafeDownCast(data))
      {
        singleBlock = vtkUniformGrid::New();
        singleBlock->ShallowCopy(ugData);
      }
      else
      {
        singleBlock = vtkImageData::New();
        singleBlock->ShallowCopy(imData);
      }
      singleBlock->SetExtent(this->FullExtent.GetData());
      this->ImageDataBlocks.push_back(singleBlock);
    }
    else if (rGrid)
    {
      vtkRectilinearGrid* singleBlock = vtkRectilinearGrid::New();
      singleBlock->ShallowCopy(rGrid);
      singleBlock->SetExtent(this->FullExtent.GetData());
      this->ImageDataBlocks.push_back(singleBlock);
    }
  }

  // Get default formats from vtkTextureObject
  if (!this->Texture)
  {
    this->Texture = vtkSmartPointer<vtkTextureObject>::New();
    this->Texture->SetContext(vtkOpenGLRenderWindow::SafeDownCast(ren->GetRenderWindow()));
  }
  if (rGrid)
  {
    if (!this->CoordsTex)
    {
      this->CoordsTex = vtkSmartPointer<vtkTextureObject>::New();
      this->CoordsTex->SetContext(vtkOpenGLRenderWindow::SafeDownCast(ren->GetRenderWindow()));
    }
  }
  if (data->GetPointGhostArray() || data->GetCellGhostArray())
  {
    this->BlankingTex = vtkSmartPointer<vtkTextureObject>::New();
    this->BlankingTex->SetContext(vtkOpenGLRenderWindow::SafeDownCast(ren->GetRenderWindow()));
  }

  int scalarType = this->Scalars->GetDataType();
  int noOfComponents = this->Scalars->GetNumberOfComponents();

  unsigned int format = this->Texture->GetDefaultFormat(scalarType, noOfComponents, false);
  unsigned int internalFormat =
    this->Texture->GetDefaultInternalFormat(scalarType, noOfComponents, false);
  int type = this->Texture->GetDefaultDataType(scalarType);

  // Resolve the appropriate texture format from the array properties
  this->SelectTextureFormat(format, internalFormat, type, scalarType, noOfComponents);
  this->CreateBlocks(format, internalFormat, type);

  // If there is a single block, load it right away since GetNextBlock() does not
  // load if streaming is disabled.
  if (this->ImageDataBlocks.size() == 1)
  {
    VolumeBlock* onlyBlock = this->SortedVolumeBlocks.at(0);
    return this->LoadTexture(this->InterpolationType, onlyBlock);
  }

  return true;
}

//------------------------------------------------------------------------------
void vtkVolumeTexture::SetInterpolation(int const interpolation)
{
  this->InterpolationType = interpolation;

  if (!this->StreamBlocks)
  {
    this->Texture->Activate();
    this->Texture->SetMagnificationFilter(interpolation);
    this->Texture->SetMinificationFilter(interpolation);
  }
}

//------------------------------------------------------------------------------
vtkVolumeTexture::VolumeBlock* vtkVolumeTexture::GetNextBlock()
{
  this->CurrentBlockIdx++;
  // All blocks were already rendered
  if (this->SortedVolumeBlocks.size() <= this->CurrentBlockIdx)
  {
    this->CurrentBlockIdx = 0;
    return nullptr;
  }
  VolumeBlock* block = this->SortedVolumeBlocks[this->CurrentBlockIdx];

  // Load current block
  if (this->StreamBlocks)
  {
    this->LoadTexture(this->InterpolationType, block);
  }

  return block;
}

//------------------------------------------------------------------------------
vtkVolumeTexture::VolumeBlock* vtkVolumeTexture::GetCurrentBlock()
{
  return this->SortedVolumeBlocks[this->CurrentBlockIdx];
}

//------------------------------------------------------------------------------
void vtkVolumeTexture::CreateBlocks(
  unsigned int const format, unsigned int const internalFormat, int const type)
{
  // Pre compute array size
  this->FullSize[0] = this->FullExtent[1] - this->FullExtent[0] + 1;
  this->FullSize[1] = this->FullExtent[3] - this->FullExtent[2] + 1;
  this->FullSize[2] = this->FullExtent[5] - this->FullExtent[4] + 1;

  size_t const numBlocks = this->ImageDataBlocks.size();
  for (size_t i = 0; i < numBlocks; i++)
  {
    vtkDataSet* dataset = this->ImageDataBlocks.at(i);
    vtkImageData* imData = vtkImageData::SafeDownCast(dataset);
    vtkRectilinearGrid* rGrid = vtkRectilinearGrid::SafeDownCast(dataset);
    int* ext = nullptr;
    if (imData)
    {
      ext = imData->GetExtent();
    }
    else if (rGrid)
    {
      ext = rGrid->GetExtent();
    }
    Size3 const texSize = this->ComputeBlockSize(ext);
    VolumeBlock* block = new VolumeBlock(dataset, this->Texture, texSize);

    // Compute tuple index (array aligned in x -> Y -> Z)
    // index = z0 * Dx * Dy + y0 * Dx + x0
    block->TupleIndex =
      ext[4] * this->FullSize[0] * this->FullSize[1] + ext[2] * this->FullSize[0] + ext[0];

    this->ImageDataBlockMap[dataset] = block;
    this->ComputeBounds(block);
    this->UpdateTextureToDataMatrix(block);
  }
  this->ComputeCellToPointMatrix(this->FullExtent.GetData());

  // Format texture
  this->Texture->SetFormat(format);
  this->Texture->SetInternalFormat(internalFormat);
  this->Texture->SetDataType(type);

  // Sorting is skipped when handling a single block, so here the block vector
  // is initialized
  if (this->ImageDataBlocks.size() == 1)
  {
    this->SortedVolumeBlocks.push_back(this->ImageDataBlockMap[this->ImageDataBlocks.at(0)]);
  }
}

//------------------------------------------------------------------------------
void vtkVolumeTexture::AdjustExtentForCell(Size6& extent)
{
  int i = 1;
  while (i < 6)
  {
    extent[i]--;
    i += 2;
  }
}

//------------------------------------------------------------------------------
vtkVolumeTexture::Size3 vtkVolumeTexture::ComputeBlockSize(int* extent)
{
  int i = 0;
  Size3 texSize;
  while (i < 3)
  {
    texSize[i] = extent[2 * i + 1] - extent[2 * i] + 1;
    ++i;
  }
  return texSize;
}

//------------------------------------------------------------------------------
bool vtkVolumeTexture::LoadTexture(int const interpolation, VolumeBlock* volBlock)
{
  int const noOfComponents = this->Scalars->GetNumberOfComponents();
  int scalarType = this->Scalars->GetDataType();

  auto dataSet = volBlock->DataSet;
  auto imBlock = vtkImageData::SafeDownCast(dataSet);
  auto rgBlock = vtkRectilinearGrid::SafeDownCast(dataSet);
  int blockExt[6];
  if (imBlock)
  {
    imBlock->GetExtent(blockExt);
  }
  else if (rgBlock)
  {
    rgBlock->GetExtent(blockExt);
  }
  Size3 const& blockSize = volBlock->TextureSize;
  vtkTextureObject* texture = volBlock->TextureObject;
  vtkIdType const& tupleIdx = volBlock->TupleIndex;

  auto ostate = texture->GetContext()->GetState();

  bool success = true;
  if (!this->HandleLargeDataTypes)
  {
    // Adjust strides used by OpenGL to load the data (X and Y strides in case the
    // texture had to be split on those axis).
    bool const useXStride = blockSize[0] != this->FullSize[0];
    if (useXStride)
    {
      ostate->vtkglPixelStorei(GL_UNPACK_ROW_LENGTH, this->FullSize[0]);
    }

    bool const useYStride = blockSize[1] != this->FullSize[1];
    if (useYStride)
    {
      ostate->vtkglPixelStorei(GL_UNPACK_IMAGE_HEIGHT, this->FullSize[1]);
    }

    // Account for component offset
    // index = ( z0 * Dx * Dy + y0 * Dx + x0 ) * numComp
    vtkIdType const dataIdx = tupleIdx * noOfComponents;
    void* dataPtr = this->Scalars->GetVoidPointer(dataIdx);

    if (this->StreamBlocks)
    {
      success = texture->Create3DFromRaw(
        blockSize[0], blockSize[1], blockSize[2], noOfComponents, scalarType, dataPtr);
    }
    else
    {
      success = SafeLoadTexture(
        texture, blockSize[0], blockSize[1], blockSize[2], noOfComponents, scalarType, dataPtr);
    }
    texture->Activate();
    texture->SetWrapS(vtkTextureObject::ClampToEdge);
    texture->SetWrapT(vtkTextureObject::ClampToEdge);
    texture->SetWrapR(vtkTextureObject::ClampToEdge);
    texture->SetMagnificationFilter(interpolation);
    texture->SetMinificationFilter(interpolation);
    texture->SetBorderColor(0.0f, 0.0f, 0.0f, 0.0f);

    if (useXStride)
    {
      ostate->vtkglPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    }

    if (useYStride)
    {
      ostate->vtkglPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0);
    }
  }
  else // Handle 64-bit types
  {
    // 64-bit types are cast to float and then streamed slice by slice into
    // GPU memory. Assumes GL_ARB_texture_non_power_of_two is available.

    scalarType = VTK_FLOAT;
    if (this->StreamBlocks)
    {
      success = texture->Create3DFromRaw(
        blockSize[0], blockSize[1], blockSize[2], noOfComponents, scalarType, nullptr);
    }
    else
    {
      success = SafeLoadTexture(
        texture, blockSize[0], blockSize[1], blockSize[2], noOfComponents, scalarType, nullptr);
    }
    texture->Activate();
    texture->SetWrapS(vtkTextureObject::ClampToEdge);
    texture->SetWrapT(vtkTextureObject::ClampToEdge);
    texture->SetWrapR(vtkTextureObject::ClampToEdge);
    texture->SetMagnificationFilter(interpolation);
    texture->SetMinificationFilter(interpolation);
    texture->SetBorderColor(0.0f, 0.0f, 0.0f, 0.0f);

    vtkFloatArray* sliceArray = vtkFloatArray::New();
    sliceArray->SetNumberOfComponents(noOfComponents);
    sliceArray->SetNumberOfTuples(blockSize[0] * blockSize[1]);

    int k = 0;
    vtkIdType const kInc = this->FullSize[0] * this->FullSize[1];
    vtkIdType kOffset = tupleIdx;

    float* tupPtr = new float[noOfComponents];
    while (k < blockSize[2])
    {
      int j = 0;
      vtkIdType jOffset = 0;
      vtkIdType jDestOffset = 0;
      while (j < blockSize[1])
      {
        int i = 0;
        while (i < blockSize[0])
        {
          // Set components
          double* scalarPtr = this->Scalars->GetTuple(kOffset + jOffset + i);
          for (int n = 0; n < noOfComponents; ++n)
          {
            tupPtr[n] = scalarPtr[n] * this->Scale[n] + this->Bias[n];
          }

          sliceArray->SetTuple(jDestOffset + i, tupPtr);
          ++i;
        }

        ++j;
        jOffset += this->FullSize[0];
        jDestOffset += blockSize[0];
      }

      void* slicePtr = static_cast<void*>(sliceArray->GetPointer(0));
      GLint format = texture->GetFormat(scalarType, noOfComponents, false);
      GLenum type = texture->GetDataType(scalarType);
      glTexSubImage3D(
        GL_TEXTURE_3D, 0, 0, 0, k, blockSize[0], blockSize[1], 1, format, type, slicePtr);

      ++k;
      kOffset += kInc;
    }

    delete[] tupPtr;
    sliceArray->Delete();
  }

  if (rgBlock)
  {
    vtkDataArray* xCoords = rgBlock->GetXCoordinates();
    this->CoordsTexSizes[0] = xCoords->GetNumberOfTuples();
    float fRange[2];
    double* r = xCoords->GetFiniteRange(0);
    for (int i = 0; i < 2; ++i)
    {
      fRange[i] = static_cast<float>(r[i]);
    }
    vtkVolumeTexture::GetScaleAndBias(VTK_FLOAT, fRange, this->CoordsScale[0], this->CoordsBias[0]);
    vtkDataArray* yCoords = rgBlock->GetYCoordinates();
    this->CoordsTexSizes[1] = yCoords->GetNumberOfTuples();
    r = yCoords->GetFiniteRange(0);
    for (int i = 0; i < 2; ++i)
    {
      fRange[i] = static_cast<float>(r[i]);
    }
    vtkVolumeTexture::GetScaleAndBias(VTK_FLOAT, fRange, this->CoordsScale[1], this->CoordsBias[1]);
    vtkDataArray* zCoords = rgBlock->GetZCoordinates();
    this->CoordsTexSizes[2] = zCoords->GetNumberOfTuples();
    r = zCoords->GetFiniteRange(0);
    for (int i = 0; i < 2; ++i)
    {
      fRange[i] = static_cast<float>(r[i]);
    }
    vtkVolumeTexture::GetScaleAndBias(VTK_FLOAT, fRange, this->CoordsScale[2], this->CoordsBias[2]);

    vtkNew<vtkFloatArray> coordsArray;
    coordsArray->SetNumberOfComponents(3);
    int numTuples = std::max(this->CoordsTexSizes[0], this->CoordsTexSizes[1]);
    numTuples = std::max(numTuples, this->CoordsTexSizes[2]);
    coordsArray->SetNumberOfTuples(numTuples);
    for (int i = 0; i < this->CoordsTexSizes[0]; ++i)
    {
      coordsArray->SetTypedComponent(i, 0,
        static_cast<float>(xCoords->GetTuple1(i) * this->CoordsScale[0] + this->CoordsBias[0]));
    }
    for (int i = 0; i < this->CoordsTexSizes[1]; ++i)
    {
      coordsArray->SetTypedComponent(i, 1,
        static_cast<float>(yCoords->GetTuple1(i) * this->CoordsScale[1] + this->CoordsBias[1]));
    }
    for (int i = 0; i < this->CoordsTexSizes[2]; ++i)
    {
      coordsArray->SetTypedComponent(i, 2,
        static_cast<float>(zCoords->GetTuple1(i) * this->CoordsScale[2] + this->CoordsBias[2]));
    }

    void* coordsPtr = static_cast<void*>(coordsArray->GetPointer(0));
    this->CoordsTex->Create1DFromRaw(numTuples, 3, VTK_FLOAT, coordsPtr);
    this->CoordsTex->SetWrapR(vtkTextureObject::ClampToEdge);
    this->CoordsTex->SetWrapS(vtkTextureObject::ClampToEdge);
    this->CoordsTex->SetWrapT(vtkTextureObject::ClampToEdge);
    this->CoordsTex->SetMagnificationFilter(vtkTextureObject::Nearest);
    this->CoordsTex->SetMinificationFilter(vtkTextureObject::Nearest);
    this->CoordsTex->SetBorderColor(0.0f, 0.0f, 0.0f, 0.0f);
  }

  vtkSmartPointer<vtkUnsignedCharArray> ugCellBlankArray = dataSet->GetCellGhostArray();
  vtkSmartPointer<vtkUnsignedCharArray> ugPointBlankArray = dataSet->GetPointGhostArray();
  // Not relying on HasAnyBlankCells because it also does the additional step of checking point
  // ghost array to determine if any cells are blanked.
  bool blankCells = (ugCellBlankArray != nullptr);
  bool blankPoints = (ugPointBlankArray != nullptr);
  if (blankCells || blankPoints)
  {
    vtkNew<vtkUnsignedCharArray> blankingArray;
    auto numComps = (blankCells && blankPoints) ? 2 : 1;
    blankingArray->SetNumberOfComponents(numComps);
    auto numPts = dataSet->GetNumberOfPoints();
    blankingArray->SetNumberOfTuples(numPts);
    blankingArray->FillValue(0);

    auto blankingArrayRange = vtk::DataArrayTupleRange(blankingArray);
    if (blankPoints)
    {
      const auto blankPointsRange = vtk::DataArrayValueRange<1>(ugPointBlankArray);
      int d0 = (blockSize[0] - this->IsCellData) * (blockSize[1] - this->IsCellData);
      int ptId, cellId;
      for (int k = 0; k < blockSize[2]; ++k)
      {
        for (int j = 0; j < blockSize[1]; ++j)
        {
          for (int i = 0; i < blockSize[0]; ++i)
          {
            cellId = k * d0 + j * (blockSize[0] - this->IsCellData) + i;
            ptId = k * (blockSize[0]) * (blockSize[1]) + j * (blockSize[0]) + i;
            blankingArrayRange[cellId][0] = blankPointsRange[ptId];
          }
        }
      }
    }

    if (blankCells)
    {
      int isPointData = this->IsCellData ? 0 : 1;
      int comp = blankPoints ? 1 : 0;
      int d0 = (blockSize[0] - isPointData) * (blockSize[1] - isPointData);
      int d01 = (blockSize[0]) * (blockSize[1]);
      const auto blankCellsRange = vtk::DataArrayValueRange<1>(ugCellBlankArray);
      int ptId, cellId;
      for (int k = 0; k < blockSize[2] - isPointData; ++k)
      {
        for (int j = 0; j < blockSize[1] - isPointData; ++j)
        {
          for (int i = 0; i < blockSize[0] - isPointData; ++i)
          {
            ptId = k * d01 + j * (blockSize[0]) + i;
            cellId = k * d0 + j * (blockSize[0] - isPointData) + i;
            if (isPointData)
            {
              auto kc = (k >= (blockSize[2] - 1) ? blockSize[2] - 2 : k);
              auto jc = (j >= (blockSize[1] - 1) ? blockSize[1] - 2 : j);
              auto ic = (i >= (blockSize[0] - 1) ? blockSize[0] - 2 : i);
              cellId = kc * d0 + jc * (blockSize[0] - 1) + ic;
            }
            blankingArrayRange[ptId][comp] = blankCellsRange[cellId];
          }
        }
      }
    }

    // Since this is a pseudo-bit array i.e. values either 0 or 255, skip scale and bias
    // computation
    this->BlankingTex->Create3DFromRaw(blockSize[0], blockSize[1], blockSize[2], numComps,
      VTK_UNSIGNED_CHAR, &blankingArrayRange[0][0]);
    this->BlankingTex->SetWrapR(vtkTextureObject::ClampToEdge);
    this->BlankingTex->SetWrapS(vtkTextureObject::ClampToEdge);
    this->BlankingTex->SetWrapT(vtkTextureObject::ClampToEdge);
    this->BlankingTex->SetMagnificationFilter(vtkTextureObject::Nearest);
    this->BlankingTex->SetMinificationFilter(vtkTextureObject::Nearest);
    this->BlankingTex->SetBorderColor(0.0f, 0.0f, 0.0f, 0.0f);
  }

  texture->Deactivate();
  this->UploadTime.Modified();

  return success;
}

//------------------------------------------------------------------------------
void vtkVolumeTexture::ReleaseGraphicsResources(vtkWindow* win)
{
  if (this->Texture)
  {
    this->Texture->ReleaseGraphicsResources(win);
    this->Texture = nullptr;
  }
}

//------------------------------------------------------------------------------
void vtkVolumeTexture::ClearBlocks()
{
  if (this->ImageDataBlocks.empty())
  {
    return;
  }

  size_t const numBlocks = this->ImageDataBlocks.size();
  for (size_t i = 0; i < numBlocks; i++)
  {
    this->ImageDataBlocks.at(i)->Delete();
    delete this->SortedVolumeBlocks.at(i);
  }

  this->CurrentBlockIdx = 0;
  this->ImageDataBlocks.clear();
  this->SortedVolumeBlocks.clear();
  this->ImageDataBlockMap.clear();
}

//------------------------------------------------------------------------------
void vtkVolumeTexture::SplitVolume(vtkImageData* imageData, Size3 const& part)
{
  Size6& fullExt = this->FullExtent;
  double const numBlocks_x = part[0];
  double const numBlocks_y = part[1];
  double const numBlocks_z = part[2];
  double const deltaX = (fullExt[1] - fullExt[0]) / numBlocks_x;
  double const deltaY = (fullExt[3] - fullExt[2]) / numBlocks_y;
  double const deltaZ = (fullExt[5] - fullExt[4]) / numBlocks_z;
  unsigned int const numBlocks = static_cast<unsigned int>(numBlocks_x * numBlocks_y * numBlocks_z);

  this->ImageDataBlocks = std::vector<vtkDataSet*>();
  this->ImageDataBlocks.reserve(numBlocks);
  this->SortedVolumeBlocks.reserve(numBlocks);

  for (int k = 0; k < static_cast<int>(numBlocks_z); k++)
  {
    for (int j = 0; j < static_cast<int>(numBlocks_y); j++)
    {
      for (int i = 0; i < static_cast<int>(numBlocks_x); i++)
      {
        Size6 ext;
        ext[0] = fullExt[0] + i * deltaX;
        ext[1] = fullExt[0] + (i + 1) * deltaX;
        ext[2] = fullExt[2] + j * deltaY;
        ext[3] = fullExt[2] + (j + 1) * deltaY;
        ext[4] = fullExt[4] + k * deltaZ;
        ext[5] = fullExt[4] + (k + 1) * deltaZ;

        // Adjust extents depending on the data representation (cell or point) and
        // compute texture size.
        if (this->IsCellData == 1)
        {
          this->AdjustExtentForCell(ext);
        }

        // Create a proxy vtkImageData object for each block
        vtkImageData* block = vtkImageData::New();
        block->ShallowCopy(imageData);
        block->SetExtent(ext[0], ext[1], ext[2], ext[3], ext[4], ext[5]);
        this->ImageDataBlocks.push_back(block);
      }
    }
  }
}

//------------------------------------------------------------------------------
void vtkVolumeTexture::GetScaleAndBias(
  const int scalarType, float* scalarRange, float& scale, float& bias)
{
  scale = 1.0f;
  bias = 0.0f;
  double glScale = 1.0;
  double glBias = 0.0;

  switch (scalarType)
  {
    case VTK_UNSIGNED_CHAR:
      glScale = 1.0 / (VTK_UNSIGNED_CHAR_MAX + 1);
      glBias = 0.0;
      break;
    case VTK_SIGNED_CHAR:
      glScale = 2.0 / (VTK_UNSIGNED_CHAR_MAX + 1);
      glBias = -1.0 - VTK_SIGNED_CHAR_MIN * glScale;
      break;
    case VTK_SHORT:
      glScale = 2.0 / (VTK_UNSIGNED_SHORT_MAX + 1);
      glBias = -1.0 - VTK_SHORT_MIN * glScale;
      break;
    case VTK_UNSIGNED_SHORT:
      glScale = 1.0 / (VTK_UNSIGNED_SHORT_MAX + 1);
      glBias = 0.0;
      break;
    case VTK_CHAR:
    case VTK_BIT:
    case VTK_ID_TYPE:
    case VTK_STRING:
      // not supported
      assert("check: impossible case" && 0);
      break;
  }

  double glRange[2];
  for (int i = 0; i < 2; ++i)
  {
    glRange[i] = scalarRange[i] * glScale + glBias;
  }
  glRange[1] = (glRange[1] == glRange[0] ? glRange[0] + 1e-6 : glRange[1]);
  scale = static_cast<float>(1.0 / (glRange[1] - glRange[0]));
  bias = static_cast<float>(0.0 - glRange[0] * scale);
}

//------------------------------------------------------------------------------
void vtkVolumeTexture::SelectTextureFormat(unsigned int& format, unsigned int& internalFormat,
  int& type, int const scalarType, int const noOfComponents)
{
  bool supportsFloat = true;
  this->HandleLargeDataTypes = false;

  switch (scalarType)
  {
    case VTK_FLOAT:
      if (supportsFloat)
      {
        switch (noOfComponents)
        {
          case 1:
            internalFormat = GL_R32F;
            format = GL_RED;
            break;
          case 2:
            internalFormat = GL_RG32F;
            format = GL_RG;
            break;
          case 3:
            internalFormat = GL_RGB32F;
            format = GL_RGB;
            break;
          case 4:
            internalFormat = GL_RGBA32F;
            format = GL_RGBA;
            break;
        }
      }
      else
      {
        switch (noOfComponents)
        {
          case 1:
            internalFormat = GL_RED;
            format = GL_RED;
            break;
          case 2:
            internalFormat = GL_RG;
            format = GL_RG;
            break;
          case 3:
            internalFormat = GL_RGB;
            format = GL_RGB;
            break;
          case 4:
            internalFormat = GL_RGBA;
            format = GL_RGBA;
            break;
        }
      }
      break;
    case VTK_UNSIGNED_CHAR:
    case VTK_SIGNED_CHAR:
    case VTK_SHORT:
    case VTK_UNSIGNED_SHORT:
      // Nothing to be done
      break;
    case VTK_INT:
    case VTK_DOUBLE:
    case VTK_LONG:
    case VTK_LONG_LONG:
    case VTK_UNSIGNED_INT:
    case VTK_UNSIGNED_LONG:
    case VTK_UNSIGNED_LONG_LONG:
      this->HandleLargeDataTypes = true;
      type = GL_FLOAT;
      switch (noOfComponents)
      {
        case 1:
          if (supportsFloat)
          {
            internalFormat = GL_R32F;
          }
          else
          {
            internalFormat = GL_RED;
          }
          format = GL_RED;
          break;
        case 2:
          internalFormat = GL_RG;
          format = GL_RG;
          break;
        case 3:
          internalFormat = GL_RGB;
          format = GL_RGB;
          break;
        case 4:
          internalFormat = GL_RGBA;
          format = GL_RGBA;
          break;
      }
      break;
    case VTK_CHAR:
    case VTK_BIT:
    case VTK_ID_TYPE:
    case VTK_STRING:
    default:
      assert("check: impossible case" && 0);
      break;
  }

  // Cache the array's scalar range
  for (int n = 0; n < noOfComponents; ++n)
  {
    double* range = this->Scalars->GetFiniteRange(n);
    for (int i = 0; i < 2; ++i)
    {
      this->ScalarRange[n][i] = static_cast<float>(range[i]);
    }
  }

  // Pixel Transfer NI to LUT Tex.Coord. [0, 1]
  //
  // NP = P * scale + bias
  // Given two point matches a,b to c,d the formulas are:
  // scale = (d - c) / (b - a)
  // bias = c - a * scale
  // For unsigned/float types c is zero.
  int const components = vtkMath::Min(noOfComponents, 4);
  for (int n = 0; n < components; n++)
  {
    this->GetScaleAndBias(scalarType, this->ScalarRange[n], this->Scale[n], this->Bias[n]);
  }
}

//------------------------------------------------------------------------------
void vtkVolumeTexture::UpdateVolume(vtkVolumeProperty* property)
{
  if (property->GetMTime() > this->UpdateTime.GetMTime())
  {
    int const newInterp = property->GetInterpolationType();
    this->UpdateInterpolationType(newInterp);
  }

  this->UpdateTime.Modified();
}

//------------------------------------------------------------------------------
void vtkVolumeTexture::UpdateInterpolationType(int const interpolation)
{
  if (interpolation == VTK_LINEAR_INTERPOLATION &&
    this->InterpolationType != vtkTextureObject::Linear)
  {
    this->SetInterpolation(vtkTextureObject::Linear);
  }
  else if (interpolation == VTK_NEAREST_INTERPOLATION &&
    this->InterpolationType != vtkTextureObject::Nearest)
  {
    this->SetInterpolation(vtkTextureObject::Nearest);
  }
  else if (interpolation != VTK_LINEAR_INTERPOLATION && interpolation != VTK_NEAREST_INTERPOLATION)
  {
    std::cerr << "Interpolation type not supported in this mapper." << std::endl;
  }
}

//------------------------------------------------------------------------------
void vtkVolumeTexture::SortBlocksBackToFront(vtkRenderer* ren, vtkMatrix4x4* volumeMat)
{
  if (this->ImageDataBlocks.size() > 1)
  {
    vtkBlockSortHelper::BackToFront<vtkImageData> sortBlocks(ren, volumeMat);
    vtkBlockSortHelper::Sort(
      this->ImageDataBlocks.begin(), this->ImageDataBlocks.end(), sortBlocks);

    size_t const numBlocks = this->ImageDataBlocks.size();
    this->SortedVolumeBlocks.clear();
    this->SortedVolumeBlocks.reserve(numBlocks);
    for (size_t i = 0; i < numBlocks; i++)
    {
      this->SortedVolumeBlocks.push_back(this->ImageDataBlockMap[this->ImageDataBlocks[i]]);
    }

    // Load the first block
    auto firstBlock = this->SortedVolumeBlocks.at(0);
    this->LoadTexture(this->InterpolationType, firstBlock);
  }
}

//------------------------------------------------------------------------------
void vtkVolumeTexture::SetPartitions(int const x, int const y, int const z)
{
  if (x > 0 && y > 0 && z > 0)
  {
    if (x > 1 || y > 1 || z > 1)
      this->StreamBlocks = true;

    this->Partitions[0] = x;
    this->Partitions[1] = y;
    this->Partitions[2] = z;
  }
  else
  {
    this->StreamBlocks = false;
    this->Partitions[0] = this->Partitions[1] = this->Partitions[2] = 1;
  }

  this->Modified();
}

//------------------------------------------------------------------------------
const vtkVolumeTexture::Size3& vtkVolumeTexture::GetPartitions()
{
  return this->Partitions;
}

//------------------------------------------------------------------------------
void vtkVolumeTexture::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);

  os << indent << "HandleLargeDataTypes: " << this->HandleLargeDataTypes << '\n';
  os << indent << "GL Scale: " << this->Scale[0] << ", " << this->Scale[1] << ", " << this->Scale[2]
     << ", " << this->Scale[3] << '\n';
  os << indent << "GL Bias: " << this->Bias[0] << ", " << this->Bias[1] << ", " << this->Bias[2]
     << ", " << this->Bias[3] << '\n';
  os << indent << "InterpolationType: " << this->InterpolationType << '\n';
  os << indent << "UploadTime: " << this->UploadTime << '\n';
  os << indent << "CurrentBlockIdx: " << this->CurrentBlockIdx << '\n';
  os << indent << "StreamBlocks: " << this->StreamBlocks << '\n';
}

//------------------------------------------------------------------------------
bool vtkVolumeTexture::AreDimensionsValid(
  vtkTextureObject* texture, int const width, int const height, int const depth)
{
  int const maxSize = texture->GetMaximumTextureSize3D();
  if (width > maxSize || height > maxSize || depth > maxSize)
  {
    std::cout << "ERROR: OpenGL MAX_3D_TEXTURE_SIZE is " << maxSize << "\n";
    return false;
  }

  return true;
}

//------------------------------------------------------------------------------
bool vtkVolumeTexture::SafeLoadTexture(vtkTextureObject* texture, int const width, int const height,
  int const depth, int numComps, int dataType, void* dataPtr)
{
  if (!AreDimensionsValid(texture, width, height, depth))
  {
    vtkErrorMacro(<< "Invalid texture dimensions [" << width << ", " << height << ", " << depth
                  << "]");
    return false;
  }

  if (!texture->AllocateProxyTexture3D(width, height, depth, numComps, dataType))
  {
    vtkErrorMacro(<< "Capabilities check via proxy texture 3D allocation "
                     "failed!");
    return false;
  }

  if (!texture->Create3DFromRaw(width, height, depth, numComps, dataType, dataPtr))
  {
    vtkErrorMacro(<< "Texture 3D allocation failed! \n");
    return false;
  }

  return true;
}

//------------------------------------------------------------------------------
void vtkVolumeTexture::ComputeBounds(VolumeBlock* block)
{
  vtkImageData* imData = vtkImageData::SafeDownCast(block->DataSet);
  vtkRectilinearGrid* rGrid = vtkRectilinearGrid::SafeDownCast(block->DataSet);
  double spacing[3];
  double origin[3];
  double* direction = nullptr;
  if (imData)
  {
    imData->GetSpacing(spacing); /// TODO could be causing inf issue on streaming
    imData->GetExtent(block->Extents);
    imData->GetOrigin(origin);
    direction = imData->GetDirectionMatrix()->GetData();
  }
  else if (rGrid)
  {
    double bounds[6];
    int dims[3];
    rGrid->GetBounds(bounds);
    rGrid->GetDimensions(dims);
    for (int cc = 0; cc < 3; ++cc)
    {
      spacing[cc] = (bounds[2 * cc + 1] - bounds[2 * cc]) / dims[cc];
      origin[cc] = bounds[2 * cc];
    }
    rGrid->GetExtent(block->Extents);
    if (this->IsCellData)
    {
      block->Extents[1]--;
      block->Extents[3]--;
      block->Extents[5]--;
    }
  }

  int swapBounds[3];
  swapBounds[0] = (spacing[0] < 0);
  swapBounds[1] = (spacing[1] < 0);
  swapBounds[2] = (spacing[2] < 0);

  // push corners through matrix to get bounding box
  int iMin, iMax, jMin, jMax, kMin, kMax;
  int* extent = block->Extents;
  iMin = extent[0];
  iMax = extent[1] + this->IsCellData;
  jMin = extent[2];
  jMax = extent[3] + this->IsCellData;
  kMin = extent[4];
  kMax = extent[5] + this->IsCellData;
  int ijkCorners[8][3] = { { iMin, jMin, kMin }, { iMax, jMin, kMin }, { iMin, jMax, kMin },
    { iMax, jMax, kMin }, { iMin, jMin, kMax }, { iMax, jMin, kMax }, { iMin, jMax, kMax },
    { iMax, jMax, kMax } };
  double xMin, xMax, yMin, yMax, zMin, zMax;
  xMin = yMin = zMin = VTK_DOUBLE_MAX;
  xMax = yMax = zMax = VTK_DOUBLE_MIN;
  for (int i = 0; i < 8; ++i)
  {
    int* ijkCorner = ijkCorners[i];
    double* xyz = block->VolumeGeometry + i * 3;
    if (imData)
    {
      vtkImageData::TransformContinuousIndexToPhysicalPoint(
        ijkCorner[0], ijkCorner[1], ijkCorner[2], origin, spacing, direction, xyz);
    }
    else if (rGrid)
    {
      rGrid->GetPoint(ijkCorner[0], ijkCorner[1], ijkCorner[2], xyz);
    }
    if (xyz[0] < xMin)
      xMin = xyz[0];
    if (xyz[0] > xMax)
      xMax = xyz[0];
    if (xyz[1] < yMin)
      yMin = xyz[1];
    if (xyz[1] > yMax)
      yMax = xyz[1];
    if (xyz[2] < zMin)
      zMin = xyz[2];
    if (xyz[2] > zMax)
      zMax = xyz[2];
  }
  block->LoadedBoundsAA[0] = xMin;
  block->LoadedBoundsAA[1] = xMax;
  block->LoadedBoundsAA[2] = yMin;
  block->LoadedBoundsAA[3] = yMax;
  block->LoadedBoundsAA[4] = zMin;
  block->LoadedBoundsAA[5] = zMax;

  // Loaded data represents points
  if (!this->IsCellData)
  {
    if (imData)
    {
      // If spacing is negative, we may have to rethink the equation
      // between real point and texture coordinate...
      block->LoadedBounds[0] =
        origin[0] + static_cast<double>(block->Extents[0 + swapBounds[0]]) * spacing[0];
      block->LoadedBounds[2] =
        origin[1] + static_cast<double>(block->Extents[2 + swapBounds[1]]) * spacing[1];
      block->LoadedBounds[4] =
        origin[2] + static_cast<double>(block->Extents[4 + swapBounds[2]]) * spacing[2];
      block->LoadedBounds[1] =
        origin[0] + static_cast<double>(block->Extents[1 - swapBounds[0]]) * spacing[0];
      block->LoadedBounds[3] =
        origin[1] + static_cast<double>(block->Extents[3 - swapBounds[1]]) * spacing[1];
      block->LoadedBounds[5] =
        origin[2] + static_cast<double>(block->Extents[5 - swapBounds[2]]) * spacing[2];
    }
    else if (rGrid)
    {
      double xyzMin[3], xyzMax[3];
      rGrid->GetPoint(block->Extents[0], block->Extents[2], block->Extents[4], xyzMin);
      rGrid->GetPoint(block->Extents[1], block->Extents[3], block->Extents[5], xyzMax);
      for (int i = 0; i < 3; ++i)
      {
        block->LoadedBounds[2 * i] = xyzMin[i];
        block->LoadedBounds[2 * i + 1] = xyzMax[i];
      }
    }
  }
  // Loaded extents represent cells
  else
  {
    if (imData)
    {
      for (int i = 0; i < 3; ++i)
      {
        block->LoadedBounds[2 * i + swapBounds[i]] =
          origin[i] + (static_cast<double>(block->Extents[2 * i])) * spacing[i];

        block->LoadedBounds[2 * i + 1 - swapBounds[i]] =
          origin[i] + (static_cast<double>(block->Extents[2 * i + 1]) + 1.0) * spacing[i];
      }
    }
    else if (rGrid)
    {
      double xyzMin[3], xyzMax[3];
      rGrid->GetPoint(block->Extents[0], block->Extents[2], block->Extents[4], xyzMin);
      rGrid->GetPoint(block->Extents[1] + 1, block->Extents[3] + 1, block->Extents[5] + 1, xyzMax);
      for (int i = 0; i < 3; ++i)
      {
        block->LoadedBounds[2 * i] = xyzMin[i];
        block->LoadedBounds[2 * i + 1] = xyzMax[i];
      }
    }
  }

  // Update sampling distance
  block->DatasetStepSize[0] = 1.0 / (block->LoadedBounds[1] - block->LoadedBounds[0]);
  block->DatasetStepSize[1] = 1.0 / (block->LoadedBounds[3] - block->LoadedBounds[2]);
  block->DatasetStepSize[2] = 1.0 / (block->LoadedBounds[5] - block->LoadedBounds[4]);

  // Cell step/scale are adjusted per block.
  // Step should be dependent on the bounds and not on the texture size
  // since we can have a non-uniform voxel size / spacing / aspect ratio.
  block->CellStep[0] = (1.f / static_cast<float>(block->Extents[1] - block->Extents[0]));
  block->CellStep[1] = (1.f / static_cast<float>(block->Extents[3] - block->Extents[2]));
  block->CellStep[2] = (1.f / static_cast<float>(block->Extents[5] - block->Extents[4]));

  this->CellSpacing[0] = static_cast<float>(spacing[0]);
  this->CellSpacing[1] = static_cast<float>(spacing[1]);
  this->CellSpacing[2] = static_cast<float>(spacing[2]);
}

//------------------------------------------------------------------------------
void vtkVolumeTexture::UpdateTextureToDataMatrix(VolumeBlock* block)
{
  // take the 0.0 to 1.0 texture coordinates and map them into
  // physical/dataset coordinates.
  vtkImageData* imData = vtkImageData::SafeDownCast(block->DataSet);
  vtkRectilinearGrid* rGrid = vtkRectilinearGrid::SafeDownCast(block->DataSet);

  double origin[3];
  double spacing[3];
  vtkMatrix3x3* directionMat = vtkMatrix3x3::New();
  directionMat->Identity();
  if (imData)
  {
    directionMat->DeepCopy(imData->GetDirectionMatrix()->GetData());
    imData->GetOrigin(origin);
    imData->GetSpacing(spacing);
  }

  auto stepsize = block->DatasetStepSize;
  vtkMatrix4x4* matrix = block->TextureToDataset;
  matrix->Identity();
  double* result = matrix->GetData();

  // Scale diag (1.0 -> world coord width)
  double* direction = directionMat->GetData();
  for (int i = 0; i < 3; ++i)
  {
    result[i * 4] = direction[i * 3] / stepsize[0];
    result[i * 4 + 1] = direction[i * 3 + 1] / stepsize[1];
    result[i * 4 + 2] = direction[i * 3 + 2] / stepsize[2];
  }

  double blockOrigin[3];
  if (imData)
  {
    vtkImageData::TransformContinuousIndexToPhysicalPoint(block->Extents[0], block->Extents[2],
      block->Extents[4], origin, spacing, direction, blockOrigin);
  }
  else if (rGrid)
  {
    rGrid->GetPoint(block->Extents[0], block->Extents[2], block->Extents[4], blockOrigin);
  }

  // Translation vec
  result[3] = blockOrigin[0];
  result[7] = blockOrigin[1];
  result[11] = blockOrigin[2];

  auto matrixInv = block->TextureToDatasetInv.GetPointer();
  matrixInv->DeepCopy(matrix);
  matrixInv->Invert();

  directionMat->Delete();
}

//------------------------------------------------------------------------------
void vtkVolumeTexture::ComputeCellToPointMatrix(int extents[6])
{
  this->CellToPointMatrix->Identity();
  this->AdjustedTexMin[0] = this->AdjustedTexMin[1] = this->AdjustedTexMin[2] = 0.0f;
  this->AdjustedTexMin[3] = 1.0f;
  this->AdjustedTexMax[0] = this->AdjustedTexMax[1] = this->AdjustedTexMax[2] = 1.0f;
  this->AdjustedTexMax[3] = 1.0f;

  if (!this->IsCellData) // point data
  {
    // Extents are one minus the number of elements
    // so we have to add 1 to it to account for
    // number of elements in any cell or point image
    // data.
    float delta[3];
    delta[0] = extents[1] - extents[0] + 1;
    delta[1] = extents[3] - extents[2] + 1;
    delta[2] = extents[5] - extents[4] + 1;

    float min[3];
    min[0] = delta[0] > 0.0 ? 0.5f / delta[0] : 0.5f;
    min[1] = delta[1] > 0.0 ? 0.5f / delta[1] : 0.5f;
    min[2] = delta[2] > 0.0 ? 0.5f / delta[2] : 0.5f;

    float range[3]; // max - min
    range[0] = (delta[0] - 0.5f) / delta[0] - min[0];
    range[1] = (delta[1] - 0.5f) / delta[1] - min[1];
    range[2] = (delta[2] - 0.5f) / delta[2] - min[2];

    this->CellToPointMatrix->SetElement(0, 0, range[0]); // Scale diag
    this->CellToPointMatrix->SetElement(1, 1, range[1]);
    this->CellToPointMatrix->SetElement(2, 2, range[2]);
    this->CellToPointMatrix->SetElement(0, 3, min[0]); // t vector
    this->CellToPointMatrix->SetElement(1, 3, min[1]);
    this->CellToPointMatrix->SetElement(2, 3, min[2]);

    // Adjust limit coordinates for texture access.
    float const zeros[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; // GL tex min
    float const ones[4] = { 1.0f, 1.0f, 1.0f, 1.0f };  // GL tex max
    this->CellToPointMatrix->MultiplyPoint(zeros, this->AdjustedTexMin);
    this->CellToPointMatrix->MultiplyPoint(ones, this->AdjustedTexMax);
  }
}

//------------------------------------------------------------------------------
vtkDataArray* vtkVolumeTexture::GetLoadedScalars()
{
  return this->Scalars;
}
VTK_ABI_NAMESPACE_END