vtkVolumeProVP1000Mapper.cxx 42.6 KB
Newer Older
1 2 3 4 5
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkVolumeProVP1000Mapper.cxx

6
  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
7 8
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
9

10 11
     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
12
     PURPOSE.  See the above copyright notice for more information.
13 14 15

=========================================================================*/
#include "vtkVolumeProVP1000Mapper.h"
Andy Cedilnik's avatar
Andy Cedilnik committed
16 17

#include "vtkCamera.h"
Andy Cedilnik's avatar
Andy Cedilnik committed
18
#include "vtkColorTransferFunction.h"
Andy Cedilnik's avatar
Andy Cedilnik committed
19 20
#include "vtkDebugLeaks.h"
#include "vtkGraphicsFactory.h"
Ken Martin's avatar
Ken Martin committed
21
#include "vtkImageData.h"
Andy Cedilnik's avatar
Andy Cedilnik committed
22
#include "vtkLight.h"
Andy Cedilnik's avatar
Andy Cedilnik committed
23
#include "vtkLightCollection.h"
Andy Cedilnik's avatar
Andy Cedilnik committed
24
#include "vtkObjectFactory.h"
25
#include "vtkOpenGLVolumeProVP1000Mapper.h"
Andy Cedilnik's avatar
Andy Cedilnik committed
26
#include "vtkPiecewiseFunction.h"
Ken Martin's avatar
Ken Martin committed
27
#include "vtkPointData.h"
28 29 30
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkToolkits.h"
Ken Martin's avatar
Ken Martin committed
31
#include "vtkTransform.h"
Andy Cedilnik's avatar
Andy Cedilnik committed
32
#include "vtkVolume.h"
33
#include "vtkVolumeProperty.h"
34

Amy Squillacote's avatar
Amy Squillacote committed
35
#include <stdio.h>
Brad King's avatar
Brad King committed
36 37
#include <math.h>

38
vtkCxxRevisionMacro(vtkVolumeProVP1000Mapper, "1.27");
39 40 41

//----------------------------------------------------------------------------
// Needed when we don't use the vtkStandardNewMacro.
Andy Cedilnik's avatar
Andy Cedilnik committed
42
vtkInstantiatorNewMacro(vtkVolumeProVP1000Mapper);
43
//----------------------------------------------------------------------------
Amy Squillacote's avatar
Amy Squillacote committed
44

45 46 47 48 49
vtkVolumeProVP1000Mapper::vtkVolumeProVP1000Mapper()
{
  VLIStatus         status;
  VLIConfiguration  *config;

50 51 52 53
  this->ImageBuffer = NULL;
  this->DepthBuffer = NULL;

  // Establish a connection with vli
54
  status = VLIOpen();
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
  if ( status != kVLIOK )
    {
    vtkDebugMacro( << "VLIOpen failed!" );
    this->Context = NULL;
    this->LookupTable = NULL;

    if ( status == kVLIErrNoHardware )
      {
      this->NoHardware = 1;
      }
    else if ( status == kVLIErrVersion )
      {
      this->WrongVLIVersion = 1;
      }
    return;
    }

  // Gather some useful information
  config = new VLIConfiguration;
  this->NumberOfBoards = config->GetNumberOfBoards();
  this->MajorBoardVersion = config->GetBoardMajorVersion();
  this->MinorBoardVersion = config->GetBoardMinorVersion();
  this->GradientTableSize = config->GetGradientTableLength();
  delete config;

  // Create the context
  this->Context = VLIContext::Create();
  if (!this->Context)
    {
    vtkErrorMacro( << "Context could not be created!" );
    return;
    }

  this->LookupTable = VLILookupTable::Create(VLILookupTable::kSize4096);

  if ( !this->LookupTable )
    {
    vtkErrorMacro( << "Lookup table could not be created!" );
    return;    
    }

  this->Context->GetClassifier().SetLookupTable(kVLITable0, this->LookupTable);

  this->Cut = VLICutPlane::Create( 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 );
  
  if ( !this->Cut )
    {
    vtkErrorMacro( << "Cut plane could not be created!" );
    return;    
    }
106 107
  
  this->DrawBoundingBox = 0;
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
}



vtkVolumeProVP1000Mapper::~vtkVolumeProVP1000Mapper()
{
  int i;

  // free the lights
  if (this->NumberOfLights > 0)
    {      
    for ( i = 0; i < this->NumberOfLights; i++ )
      {
      this->Context->RemoveLight( this->Lights[i] );
      this->Lights[i]->Release();
      }
    if ( this->Lights )
      {
      delete [] this->Lights;
      }
    }
  
  if (this->Cut)
    {
    this->Cut->Release();
    }

  // Free the lookup table if it was created
  if ( this->LookupTable )
    {
    this->LookupTable->Release();
    }

  // Free the volume if necessary
  if ( this->Volume )
    {
    if (this->Volume->IsLocked() == VLItrue)
      {
      this->Volume->UnlockVolume();
      }
    this->Volume->Release();
    }

  if (this->ImageBuffer)
    {
    this->ImageBuffer->Release();
    this->ImageBuffer = NULL;
    }
156 157 158 159 160 161
  
  if (this->DepthBuffer)
    {
    this->DepthBuffer->Release();
    this->DepthBuffer = NULL;
    }
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

  // Free the context if necessary
  if (this->Context)
    {
    this->Context->Release();
    }
  
  // Terminate connection to the hardware
  VLIClose();
}

vtkVolumeProVP1000Mapper *vtkVolumeProVP1000Mapper::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkVolumeProVP1000Mapper");
  if(ret)
    {
    return (vtkVolumeProVP1000Mapper*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  const char *temp = vtkGraphicsFactory::GetRenderLibrary();
  
#ifdef VTK_USE_OGLR
  if (!strcmp("OpenGL",temp))
    {
#ifdef VTK_DEBUG_LEAKS
    vtkDebugLeaks::DestructClass("vtkVolumeProVP1000Mapper");
#endif
    return vtkOpenGLVolumeProVP1000Mapper::New();
    }
#endif
#ifdef _WIN32
  if (!strcmp("Win32OpenGL",temp))
    {
#ifdef VTK_DEBUG_LEAKS
    vtkDebugLeaks::DestructClass("vtkVolumeProVP1000Mapper");
#endif
    return vtkOpenGLVolumeProVP1000Mapper::New();
    }
#endif
  
  return new vtkVolumeProVP1000Mapper;
}



void vtkVolumeProVP1000Mapper::UpdateCamera( vtkRenderer *ren, vtkVolume * vtkNotUsed(vol) )
{
210 211 212
  double                    positionVTK[3];
  double                    focalPointVTK[3];
  double                    viewUpVTK[3];
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
  VLIStatus                 status;

  // Get the necessary information from the vtk camera
  ren->GetActiveCamera()->GetPosition( positionVTK );
  ren->GetActiveCamera()->GetFocalPoint( focalPointVTK );
  ren->GetActiveCamera()->GetViewUp( viewUpVTK );

  // make sure we are in parallel mode
  if (!ren->GetActiveCamera()->GetParallelProjection())
    {
    vtkWarningMacro("The Volume Pro VP1000 does not support perspective projection and the camera is currently not in ParallelProjection mode.");
    }

  // Create the three vectors we need to do the lookat
  VLIVector3D positionVLI ( positionVTK );
  VLIVector3D focalPointVLI ( focalPointVTK );
  VLIVector3D viewUpVLI ( viewUpVTK );

  // Create a camera from this matrix
232 233
  VLIMatrix viewMatrixVLI = VLIMatrix::LookAt(positionVLI, focalPointVLI,
                                              viewUpVLI );
234 235 236
  status = this->Context->GetCamera().SetViewMatrix( viewMatrixVLI );

  double clippingRange[2], parallelScale;
237
  double aspect[2];
238
  ren->GetActiveCamera()->GetClippingRange(clippingRange);
239
  ren->GetAspect(aspect);
240 241
  parallelScale = ren->GetActiveCamera()->GetParallelScale();

242 243
  VLIMatrix projectionMatrixVLI = VLIMatrix::Ortho(-parallelScale*aspect[0],
                                                   parallelScale*aspect[0],
244 245 246 247
                                                   -parallelScale,
                                                   parallelScale,
                                                   clippingRange[0],
                                                   clippingRange[1]);
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
  
  status = this->Context->GetCamera().SetProjectionMatrix( projectionMatrixVLI );

  if ( status != kVLIOK )
    {
    vtkErrorMacro( << "Camera matrix not set!" );
    }

  if ( this->SuperSampling )
    {
    if (this->SuperSamplingFactor[2] == 0.0)
      {
      status = this->Context->SetSamplingFactor(1.0);
      }
    else
      {
      status =
        this->Context->SetSamplingFactor(1/this->SuperSamplingFactor[2]);
      }
    if ( status != kVLIOK )
      {
      vtkErrorMacro( << "Could not set the sampling factor!" );
      }
    }
  else
    {
    this->Context->SetSamplingFactor( 1.0 );
    }
}



void vtkVolumeProVP1000Mapper::UpdateLights( vtkRenderer *ren, vtkVolume *vol )
{
  vtkLight     *light;
  float        status;
  int          count;
  int          index;
286
  double       position[3], focalPoint[3];
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
  float        intensity;
  VLIVector3D  direction;
  int          i;

  // How many lights do we have?
  count = 0;
  for( ren->GetLights()->InitTraversal(); 
      (light = ren->GetLights()->GetNextItem()); )
    {
    status = light->GetSwitch();
    if ( status > 0.0 )
      {
      count++;
      }
    }

  if ( count > this->NumberOfLights )
    {      
    for ( i = 0; i < this->NumberOfLights; i++ )
      {
      this->Context->RemoveLight( this->Lights[i] );
      this->Lights[i]->Release();
      }
    if ( this->Lights )
      {
      delete [] this->Lights;
      }

    this->NumberOfLights = count;
    this->Lights = new VLILight* [count];

    for ( i = 0; i < this->NumberOfLights; i++ )
      {
      this->Lights[i] =  VLILight::CreateDirectional( );
      this->Context->AddLight( this->Lights[i] );
      }
    }

  index = 0;
  if ( vol->GetProperty()->GetShade() )
    {
    for(ren->GetLights()->InitTraversal(); 
329
        (light = ren->GetLights()->GetNextItem()); )
330 331 332
      {
      status = light->GetSwitch();
      if ( status > 0.0 )
333 334 335 336 337 338 339 340 341 342 343 344
        {
        light->GetPosition( position );
        light->GetFocalPoint( focalPoint );
        intensity = light->GetIntensity();
        direction.Assign( (focalPoint[0] - position[0]),
                          (focalPoint[1] - position[1]),
                          (focalPoint[2] - position[2]) );
        direction.Normalize();
        this->Lights[index]->SetDirection( direction );
        this->Lights[index]->SetIntensity( intensity );
        index++;
        }
345 346 347 348 349 350 351 352 353 354
      }
    }
  
  for ( i = index; i < this->NumberOfLights; i++ )
    {
    this->Lights[i]->SetIntensity( 0.0 );
    }
}

void vtkVolumeProVP1000Mapper::UpdateProperties( vtkRenderer *vtkNotUsed(ren), 
355
                                                vtkVolume *vol )
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
{
  vtkPiecewiseFunction      *grayFunc;
  vtkPiecewiseFunction      *goFunc;
  vtkPiecewiseFunction      *soFunc;
  vtkColorTransferFunction  *rgbFunc;
  VLIuint8                  rgbTable[4096][3];
  VLIuint16                 aTable[4096];
  int                       i;
  float                     scale = 1.0;
  double                    *gradientTable;
  float                     val;

  switch ( this->VolumeDataType )
    {
    case VTK_VOLUME_8BIT:
371
      scale = 255.0 / 4095.0;
372
      break;
Amy Squillacote's avatar
Amy Squillacote committed
373 374 375
    case VTK_VOLUME_12BIT_LOWER:
      scale = 1.0;
      break;
376
    case VTK_VOLUME_16BIT:
377
      scale = 65535.0 / 4095.0;
378 379 380 381 382 383 384 385 386 387
      break;
    }

  soFunc = vol->GetProperty()->GetScalarOpacity();

  switch ( vol->GetProperty()->GetColorChannels() )
    {
    case 1:
      grayFunc = vol->GetProperty()->GetGrayTransferFunction();
      for ( i= 0; i< 4096; i++)
388
        {
389
        val = 0.5 + grayFunc->GetValue(static_cast<float>(i)*scale)*255.0;
390 391
        val = (val < 0)?(0):(val);
        val = (val > 255)?(255):(val);
392 393
        rgbTable[i][0] = rgbTable[i][1] = rgbTable[i][2] 
          = static_cast<unsigned char>( val );
394
        
395
        val = 0.5 + 4095.0 * soFunc->GetValue(static_cast<float>(i)*scale);
396 397
        val = (val < 0)?(0):(val);
        val = (val > 4095)?(4095):(val);
398
        aTable[i] = static_cast<unsigned short>( val );
399
        }
400 401 402 403
      break;
    case 3:
      rgbFunc = vol->GetProperty()->GetRGBTransferFunction();
      for ( i= 0; i< 4096; i++)
404
        {
405
        val = 0.5 + rgbFunc->GetRedValue(static_cast<float>(i)*scale)*255.0;
406 407
        val = (val < 0)?(0):(val);
        val = (val > 255)?(255):(val);
408
        rgbTable[i][0] = static_cast<unsigned char>( val );
409

410
        val = 0.5 + rgbFunc->GetGreenValue(static_cast<float>(i)*scale)*255.0;
411 412
        val = (val < 0)?(0):(val);
        val = (val > 255)?(255):(val);
413
        rgbTable[i][1] = static_cast<unsigned char>( val );
414

415
        val = 0.5 + rgbFunc->GetBlueValue(static_cast<float>(i)*scale)*255.0;
416 417
        val = (val < 0)?(0):(val);
        val = (val > 255)?(255):(val);
418
        rgbTable[i][2] = static_cast<unsigned char>( val );
419

420
        val = 0.5 + 4095.0 * soFunc->GetValue(static_cast<float>(i)*scale);
421 422
        val = (val < 0)?(0):(val);
        val = (val > 4095)?(4095):(val);
423
        aTable[i] = static_cast<unsigned short>( val );
424
        }
425 426 427 428 429 430 431 432 433 434 435
      break;
    }

  this->LookupTable->SetColorEntries( 0, 4096, rgbTable );
  this->LookupTable->SetAlphaEntries( 0, 4096, aTable );

  // Set up the gradient magnitude opacity modulation
  goFunc = vol->GetProperty()->GetGradientOpacity();

  if ( !this->GradientOpacityModulation || !goFunc ||
       ( !strcmp(goFunc->GetType(), "Constant") && 
436
         goFunc->GetValue(0) == 1.0 ))
437 438 439 440 441 442 443 444 445 446
    {
    this->Context->SetGradientOpacityModulation( VLIfalse );
    }
  else
    {
    switch ( this->VolumeDataType )
      {
      case VTK_VOLUME_8BIT:
        scale = sqrt(3.0)*256.0;
        break;
447 448 449
      case VTK_VOLUME_12BIT_LOWER:
        scale = sqrt(3.0)*4096;
        break;
450 451 452 453 454 455
      case VTK_VOLUME_16BIT:
        scale = sqrt(3.0)*65536;
        break;
      }

    gradientTable = new double [this->GradientTableSize];
456 457
    double *spacing = this->GetInput()->GetSpacing();
    double avgSpacing = 0.333*(spacing[0] + spacing[1] + spacing[2]);
458 459 460 461 462 463
    scale = scale/(avgSpacing*(this->GradientTableSize-1));
    
    for ( i = 0; i < this->GradientTableSize; i++ )
      {
      // Take an average of five values in the region
      gradientTable[i] = 0.2 * ( 
464 465 466 467 468
        goFunc->GetValue(scale*(static_cast<float>(i - 0.4)))  +
        goFunc->GetValue(scale*(static_cast<float>(i-0.2))) +
        goFunc->GetValue(scale*(static_cast<float>(i))) +
        goFunc->GetValue(scale*(static_cast<float>(i+0.2))) +
        goFunc->GetValue(scale*(static_cast<float>(i+0.4))));
469 470 471 472 473 474 475 476 477 478 479
      }
    
    this->Context->SetGradientOpacityModulation( VLItrue );
    this->Context->SetGradientTable( gradientTable );
    delete [] gradientTable;
    }

  if ( vol->GetProperty()->GetShade() )
    {
    this->Context->
      SetReflectionProperties( vol->GetProperty()->GetDiffuse(),
480 481 482
                               vol->GetProperty()->GetSpecular(),
                               vol->GetProperty()->GetAmbient(),
                               vol->GetProperty()->GetSpecularPower() );
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
    }
  else
    {
    this->Context->SetReflectionProperties( 0.0, 0.0, 1.0, 1.0 );
    }

  this->Context->GetClassifier().SetLookupTable(kVLITable0, this->LookupTable);
}

void vtkVolumeProVP1000Mapper::UpdateCropping( vtkRenderer * vtkNotUsed(ren), vtkVolume * vtkNotUsed(vol) )
{
  VLICrop  *crop;

  crop = new VLICrop;

498 499 500 501 502 503
  crop->SetSlabs( this->VoxelCroppingRegionPlanes[0], 
                  this->VoxelCroppingRegionPlanes[1],
                  this->VoxelCroppingRegionPlanes[2], 
                  this->VoxelCroppingRegionPlanes[3],
                  this->VoxelCroppingRegionPlanes[4], 
                  this->VoxelCroppingRegionPlanes[5] );
504 505 506 507 508 509 510 511 512 513

  if ( !this->Cropping )
    {
    crop->SetFlags( VLICrop::kDisable );
    }
  else
    {
    switch ( this->CroppingRegionFlags )
      {
      case VTK_CROP_SUBVOLUME:
514 515
        crop->SetFlags( VLICrop::kSubVolume );
        break;
516
      case VTK_CROP_FENCE:
517 518
        crop->SetFlags( VLICrop::k3DFence );
        break;
519
      case VTK_CROP_INVERTED_FENCE:
520 521
        crop->SetFlags( VLICrop::k3DFenceInvert );
        break;
522
      case VTK_CROP_CROSS:
523 524
        crop->SetFlags( VLICrop::k3DCross );
        break;
525
      case VTK_CROP_INVERTED_CROSS:
526 527
        crop->SetFlags( VLICrop::k3DCrossInvert );
        break;
528
      default:
529 530 531
        crop->SetFlags( VLICrop::kDisable );
        vtkErrorMacro( << "Unsupported crop option!" );
        break;
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
      }
    }

  this->Context->SetCrop( *crop );

  delete crop;
}

void vtkVolumeProVP1000Mapper::UpdateCutPlane( vtkRenderer * vtkNotUsed(ren), vtkVolume *vtkNotUsed(vol) )
{
  VLIStatus   status;

  // If the cut plane is turned off, but the context has a cut plane,
  // then we need to remove it
  if ( !this->CutPlane )
    {
    // Remove it if necessary
    if ( this->Context->GetCutPlaneCount() > 0 )
      {
      status = this->Context->RemoveCutPlane( this->Cut );
      if ( status != kVLIOK )
553 554 555
        {
        vtkErrorMacro( << "Could not remove cut plane from context" );
        }
556 557 558 559 560 561 562 563 564
      }
    }
  // If the cut plane is turned on, and the context does not have a cut
  // plane, then we need to add it. Also, update the position/orientation
  // and thickness of the plane
  else
    {
    // Update the position/orientation
    status = this->Cut->SetPlane( this->CutPlaneEquation[0],
565 566 567
                                  this->CutPlaneEquation[1],
                                  this->CutPlaneEquation[2],
                                  this->CutPlaneEquation[3] );
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
    if ( status != kVLIOK )
      {
      vtkErrorMacro( << "Could not set cut plane equation" );
      }

    // Update the thickness
    status = this->Cut->SetThickness( this->CutPlaneThickness );
    if ( status != kVLIOK )
      {
      vtkErrorMacro( << "Could not set cut plane thickness" );
      }

    // Update the falloff distance
    status = this->Cut->SetFallOff( this->CutPlaneFallOffDistance );
    if ( status != kVLIOK )
      {
      vtkErrorMacro( << "Could not set cut plane fall off distance" );
      }

    // Add it if necessary
    if ( this->Context->GetCutPlaneCount() == 0 )
      {
      status = this->Context->AddCutPlane( this->Cut );
      if ( status != kVLIOK )
592 593 594
        {
        vtkErrorMacro( << "Could not remove cut plane from context" );
        }
595 596 597 598 599 600 601 602 603 604 605
      }
    }
}

void vtkVolumeProVP1000Mapper::UpdateCursor( vtkRenderer *vtkNotUsed(ren), vtkVolume *vtkNotUsed(vol) )
{
}

void vtkVolumeProVP1000Mapper::UpdateVolume( vtkRenderer * vtkNotUsed(ren), vtkVolume * vol )
{
  int                       dataSize[3];
606 607 608
  int                       dataType;
  unsigned char             *uc_data_ptr;
  unsigned short            *us_data_ptr;
609 610 611 612 613
  void                      *data_ptr;
  vtkImageData              *input = this->GetInput();
  vtkTransform              *correctionTransform;
  vtkTransform              *modelTransform;
  int                       i, j;
614 615
  double                    dataOrigin[3];
  double                    dataSpacing[3];
616
  VLIStatus                 status;
617
  double                    range[2];
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
  
  // We need the size to create the volume and check the subvolume
  input->GetDimensions( dataSize );
  VLIVolumeRange volumeRange (dataSize[0], dataSize[1], dataSize[2]);
  
  // If we have a volume, the size still matches, but our data has
  // been modified, call UpdateVolume() to change the content
  if ( this->Volume &&
       input == this->VolumeInput &&
       input->GetMTime() >= this->VolumeBuildTime->GetMTime() &&
       this->LoadedDataSize[0] == dataSize[0] && 
       this->LoadedDataSize[1] == dataSize[1] &&
       this->LoadedDataSize[2] == dataSize[2] )
    {
    int volumeUpdated = 0;
    
    // Get the data type and a void * pointer to the data
    dataType = input->GetPointData()->GetScalars()->GetDataType();
    data_ptr = input->GetPointData()->GetScalars()->GetVoidPointer(0);
    
    // Switch on data type and update the volume
    switch ( dataType )
      {
      case VTK_UNSIGNED_CHAR:
642 643
        if ( this->VolumeDataType == VTK_VOLUME_8BIT )
          {
644
          uc_data_ptr = static_cast<unsigned char *>(data_ptr);
645 646 647
          this->Volume->Update( uc_data_ptr, volumeRange );
          volumeUpdated = 1;
          }
648 649 650 651
        
        break;
        
      case VTK_UNSIGNED_SHORT:
652 653
        if ( this->VolumeDataType == VTK_VOLUME_16BIT ||
             this->VolumeDataType == VTK_VOLUME_12BIT_LOWER)
654
          {
655
          us_data_ptr = static_cast<unsigned short *>(data_ptr);
656
          this->Volume->Update(us_data_ptr, volumeRange);
657 658 659
          volumeUpdated = 1;
          }
        break;
660 661
        
      default:
662 663
        vtkErrorMacro( "You must convert your data to unsigned char or " <<
                       "unsigned short for a VolumePro mapper" );
664
        break;
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
      }
    
    if ( volumeUpdated )
      {
      this->VolumeBuildTime->Modified();
      }
    }
  
  // If we have a volume, it is the one we last built with, and it
  // has not been modified since then, then we don't need to rebuilt
  if ( !this->Volume || 
       input != this->VolumeInput ||
       input->GetMTime() >= this->VolumeBuildTime->GetMTime() )
    {
    // Otherwise, we need to build the volume
    this->VolumeInput = input;
    this->VolumeBuildTime->Modified();
    
    // If we already have one, get rid of it
    if ( this->Volume )
      {
      this->Volume->Release();
      this->Volume = NULL;
      }
    
    // Get the data type and a void * pointer to the data
    dataType = input->GetPointData()->GetScalars()->GetDataType();
    data_ptr = input->GetPointData()->GetScalars()->GetVoidPointer(0);

    // Switch on data type and create the volume
    switch ( dataType )
      {
      case VTK_UNSIGNED_CHAR:
698
        uc_data_ptr = static_cast<unsigned char *>(data_ptr);
699
        this->Volume = VLIVolume::Create( 8, dataSize[0], dataSize[1],
700 701 702 703
                                          dataSize[2], 0, 0, uc_data_ptr );
        this->Volume->SetFieldDescriptor(kVLIField0,
                                         VLIFieldDescriptor(0, 8, kVLIUnsignedFraction));
        
704
        this->VolumeDataType = VTK_VOLUME_8BIT;
705 706 707 708
        
        break;
        
      case VTK_UNSIGNED_SHORT:
709
        us_data_ptr = static_cast<unsigned short *>(data_ptr);
710 711 712
        this->Volume = VLIVolume::Create( 16, dataSize[0], dataSize[1],
                                          dataSize[2], 0, 0, us_data_ptr );
        
Amy Squillacote's avatar
Amy Squillacote committed
713
        input->GetPointData()->GetScalars()->GetRange( range );
714
        if ( range[1] > 4095 )
Amy Squillacote's avatar
Amy Squillacote committed
715 716 717 718 719 720 721 722 723 724 725 726
          {
          this->Volume->SetFieldDescriptor(kVLIField0,
                                           VLIFieldDescriptor(0, 16, kVLIUnsignedFraction));
          
          this->VolumeDataType = VTK_VOLUME_16BIT;
          }
        else
          {
          this->Volume->SetFieldDescriptor(kVLIField0,
                                           VLIFieldDescriptor(0, 12, kVLIUnsignedFraction));
          this->VolumeDataType = VTK_VOLUME_12BIT_LOWER;
          }
727
        
728
        break;
729 730
        
      default:
731 732
        vtkErrorMacro( << "You must convert your data to unsigned char or "
                       << "unsigned short for a VolumePro mapper" );
733
        break;
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
      }
    }
  
  // Keep the data size for our check next time
  this->LoadedDataSize[0] = dataSize[0];
  this->LoadedDataSize[1] = dataSize[1];
  this->LoadedDataSize[2] = dataSize[2];

  // Store the matrix of the volume in a temporary transformation matrix
  modelTransform = vtkTransform::New();
  modelTransform->SetMatrix( vol->vtkProp3D::GetMatrix() );

  // Get the origin of the data.  This translation is not accounted for in
  // the volume's matrix, so we must add it in.
  input->GetOrigin( dataOrigin );

  // Get the data spacing.  This scaling is not accounted for in
  // the volume's matrix, so we must add it in.
  input->GetSpacing( dataSpacing );

  // Create a transform that will account for the scaling and translation of
  // the scalar data
  correctionTransform = vtkTransform::New();
  correctionTransform->Identity();
  correctionTransform->Translate(dataOrigin[0], dataOrigin[1], dataOrigin[2]);
  correctionTransform->Scale( dataSpacing[0], dataSpacing[1], dataSpacing[2] );

761
  VLIMatrix     correctionMatrixVLI;
762 763 764 765 766 767 768 769 770 771
  VLIMatrix modelMatrixVLI;

  // Now copy the matrix out (inverted) into an array of doubles
  for ( j = 0; j < 4; j++ )
    for ( i = 0; i < 4; i++ )
      {
      modelMatrixVLI[i][j] = modelTransform->GetMatrix()->GetElement( i, j );
      correctionMatrixVLI[i][j] = correctionTransform->GetMatrix()->GetElement( i, j );
      }

772
  if( this->Volume )
773
    {
774 775 776 777 778
    status = this->Volume->SetCorrectionMatrix( correctionMatrixVLI );
    if ( status != kVLIOK )
      {
      vtkErrorMacro( << "Error setting the correction matrix: " << status );
      }
779 780 781 782 783 784 785 786 787 788 789 790 791
    }

  status = this->Context->GetCamera().SetModelMatrix( modelMatrixVLI );
  if ( status != kVLIOK )
    {
    vtkErrorMacro( << "Error setting the model matrix: " << status );
    }
  
  // Delete the objects we created
  correctionTransform->Delete();
  modelTransform->Delete();

  // Update the subvolume if it is reasonable
792 793
  if ( this->Volume &&
       this->SubVolume[0] >= 0 && 
794 795 796 797 798 799 800 801 802 803 804 805
       this->SubVolume[2] >= 0 &&
       this->SubVolume[4] >= 0 &&
       this->SubVolume[0] < dataSize[0] &&
       this->SubVolume[2] < dataSize[1] &&
       this->SubVolume[4] < dataSize[2] &&
       this->SubVolume[1] >= this->SubVolume[0] && 
       this->SubVolume[3] >= this->SubVolume[2] &&
       this->SubVolume[5] >= this->SubVolume[4] &&
       this->SubVolume[1] < dataSize[0] &&
       this->SubVolume[3] < dataSize[1] &&
       this->SubVolume[5] < dataSize[2] )
    {
806 807 808 809 810
    VLIVolumeRange volRange ((this->SubVolume[1]-this->SubVolume[0]) + 1,
                             (this->SubVolume[3]-this->SubVolume[2]) + 1,
                             (this->SubVolume[5]-this->SubVolume[4]) + 1,
                             this->SubVolume[0], this->SubVolume[2],
                             this->SubVolume[4] );
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
    status = 
      this->Volume->SetActiveSubVolume( volRange );
    if ( status != kVLIOK )
      {
      vtkErrorMacro( << "Could not set the active subvolume" );
      }
    }
}

int vtkVolumeProVP1000Mapper::GetAvailableBoardMemory()
{
  int               memory;
  VLIConfiguration  *config;

  config = new VLIConfiguration;
  memory = config->GetAvailableMemory( 0 );
  delete config;
  
  return memory;
}

void vtkVolumeProVP1000Mapper::GetLockSizesForBoardMemory( unsigned int type,
833 834 835
                                                     unsigned int *xSize,
                                                     unsigned int *ySize,
                                                     unsigned int *zSize )
836 837 838 839 840 841 842 843 844 845 846 847
{
  VLIConfiguration  *config;

  config = new VLIConfiguration;
  config->GetMaxLockedSize( type, *xSize, *ySize, *zSize );
  delete config;
}

void vtkVolumeProVP1000Mapper::Render( vtkRenderer *ren, vtkVolume *vol )
{
  int                       size[2];
  VLIStatus                 status;
848
  //return;
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
  
  if ( !this->StatusOK() )
    {
    return;
    }

  // make sure that we have scalar input and update the scalar input
  if ( this->GetInput() == NULL ) 
    {
    vtkErrorMacro(<< "No Input!");
    return;
    }
  else
    {    
    this->GetInput()->UpdateInformation();
    this->GetInput()->SetUpdateExtentToWholeExtent();
    this->GetInput()->Update();
    } 

868 869
  this->ConvertCroppingRegionPlanesToVoxels();
  
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
  this->UpdateCamera( ren, vol );

  this->UpdateLights( ren, vol);

  this->UpdateVolume( ren, vol );

  this->UpdateProperties( ren, vol );  

  if ( !this->Volume )
    {
    return;
    }

  this->UpdateCropping( ren, vol );

  this->UpdateCutPlane( ren, vol );

  this->UpdateCursor( ren, vol );

Lisa Avila's avatar
Lisa Avila committed
889
  this->Context->SetCorrectGradient (VLItrue);
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911

  switch ( this->BlendMode )
    {
    case VTK_BLEND_MODE_COMPOSITE:
      this->Context->SetBlendMode( kVLIBlendFTB );
      break;
    case VTK_BLEND_MODE_MAX_INTENSITY:
      this->Context->SetBlendMode( kVLIBlendMIP );
      break;
    case VTK_BLEND_MODE_MIN_INTENSITY:
      this->Context->SetBlendMode( kVLIBlendMINIP );
      break;
    default:
      vtkErrorMacro( << "Unknown blending mode: " << this->BlendMode );
      break;
    }

  int *windowSize;
  windowSize = ren->GetRenderWindow()->GetSize();
  
  status = this->Volume->LockVolume();

912 913 914 915
  if ( this->ImageBuffer )
    {
    unsigned int width, height;
    this->ImageBuffer->GetSize(width, height);
916 917
    if (static_cast<int>(width) != windowSize[0] || 
        static_cast<int>(height) != windowSize[1])
918 919 920 921 922
      {
      this->ImageBuffer->Release();
      this->ImageBuffer = NULL;
      }
    }
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
  if ( ! this->ImageBuffer )
    {
    static VLIFieldDescriptor sImageBufferFields[4] =
    {
      VLIFieldDescriptor(0, 8, kVLIUnsignedFraction),
      VLIFieldDescriptor(8, 8, kVLIUnsignedFraction),
      VLIFieldDescriptor(16, 8, kVLIUnsignedFraction),
      VLIFieldDescriptor(24, 8, kVLIUnsignedFraction)
    };
    
    this->ImageBuffer = VLIImageBuffer::Create(kVLIBoard0, windowSize[0],
                                               windowSize[1], 32, 4,
                                               sImageBufferFields);
    this->ImageBuffer->SetBorderValue(0, 0, 0, 0);
    }
  
  this->Context->SetRayTermination(1.0, VLIfalse);

941 942 943 944 945 946 947 948 949 950
  int width = 0, height = 0;
  
  this->CheckSubSampling(this->Volume, this->Context, width, height);
  
  int imageWidth, imageHeight;
  imageWidth = this->ImageBuffer->GetWidth();
  imageHeight = this->ImageBuffer->GetHeight();
  
  this->DrawBoundingBox = 0;
  
Amy Squillacote's avatar
Amy Squillacote committed
951
  if (width > imageWidth || height > imageHeight)
952
    {
Amy Squillacote's avatar
Amy Squillacote committed
953
    if (width < 2000 && height < 2000)
954
      {
Amy Squillacote's avatar
Amy Squillacote committed
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
      float aspectRatio = (float)imageWidth / (float)imageHeight;
      int widthDiff, heightDiff, newWidth, newHeight;
      float increase;
      
      widthDiff = width - imageWidth;
      heightDiff = height - imageHeight;
      if (widthDiff > heightDiff)
        {
        increase = (float)width / (float)imageWidth;
        newWidth = width;
        newHeight = ceil(imageHeight*increase);
        }
      else
        {
        increase = (float)height / (float)imageHeight;
        newWidth = ceil(imageWidth*increase);
        newHeight = height;
        }
      this->ImageBuffer->Release();
      static VLIFieldDescriptor sImageBufferFields[4] =
      {
        VLIFieldDescriptor(0, 8, kVLIUnsignedFraction),
        VLIFieldDescriptor(8, 8, kVLIUnsignedFraction),
        VLIFieldDescriptor(16, 8, kVLIUnsignedFraction),
        VLIFieldDescriptor(24, 8, kVLIUnsignedFraction)
      };
      
      this->ImageBuffer = VLIImageBuffer::Create(kVLIBoard0, newWidth,
                                                 newHeight, 32, 4,
                                                 sImageBufferFields);
      this->ImageBuffer->SetBorderValue(0, 0, 0, 0);
986 987 988
      }
    else
      {
Amy Squillacote's avatar
Amy Squillacote committed
989
      this->DrawBoundingBox = 1;
990 991 992 993 994 995
      }
    }
  
  if ( ! this->DrawBoundingBox)
    {
    if ( ! this->IntermixIntersectingGeometry )
996
      {
997
      status = this->Volume->Render(this->Context, this->ImageBuffer);
998
      }
999
    else
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
      VLIImageRange iRange = VLIImageRange(windowSize[0], windowSize[1]);
      if ( this->DepthBuffer )
        {
        unsigned int width, height;
        this->DepthBuffer->GetSize(width, height);
        if (static_cast<int>(width) != windowSize[0] || 
            static_cast<int>(height) != windowSize[1])
          {
          this->DepthBuffer->Release();
          this->DepthBuffer = NULL;
          }
        }
      if ( ! this->DepthBuffer )
        {
        this->DepthBuffer = VLIDepthBuffer::Create(kVLIBoard0, windowSize[0],
                                                   windowSize[1]);
        this->DepthBuffer->SetBorderValue(0);
        this->DepthBuffer->SetInputLimits(iRange);
        status = this->Context->SetDepthTest(VLIContext::kDepthBuffer1,
                                             VLIContext::kDepthTestLess);
        }
      unsigned int *depthData = new unsigned int[windowSize[0]*windowSize[1]];
      this->GetDepthBufferValues(ren, windowSize, depthData);
      
      status = this->DepthBuffer->Update(depthData,
                                         VLIImageRange(windowSize[0],
                                                       windowSize[1]));
      if ( status != kVLIOK )
        {
        switch ( status )
          {
          case kVLIErrArgument:
            vtkErrorMacro( << "Invalid argument for updating depth buffer!" );
            break;
          case kVLIErrAlloc:
            vtkErrorMacro( << "Not enough resources to update depth buffer!" );
            break;
          default:
            // Don't know what the error is, but can't update the depth buffer.
            // Shouldn't get to this error message.
            vtkErrorMacro( << "Unknown error updating depth buffer!" );
            break;
          }
        return;
        }
      this->ImageBuffer->Clear(iRange, 0);
      status = this->Volume->Render(this->Context, this->ImageBuffer, 0, 0,    
                                    this->DepthBuffer);
      
      delete [] depthData;
1051 1052 1053 1054 1055 1056 1057
      }
    
    if ( status != kVLIOK )
      {
      switch ( status )
        {
        case kVLIErrArgument:
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
          vtkErrorMacro( << "Volume could not be rendered - bad argument!" );
          break;
        case kVLIErrCantSubsample:
          vtkErrorMacro( << "Volume could not be rendered - volume too large for viewport!");
          break;
        case kVLIErrClassifier:
          vtkErrorMacro( << "Volume could not be rendered - invalid classifier!");
          break;
        case kVLIErrTransform:
          vtkErrorMacro( << "Volume could not be rendered - invalid transform state!");
          break;
        case kVLIErrAccess:
          vtkErrorMacro( << "Volume could not be rendered - could not access volume!" );
          break;
        case kVLIErrPermission:
          vtkErrorMacro( << "Volume could not be rendered - do not have permission to perform render!");
          break;
        case kVLIErrVolume:
          vtkErrorMacro( << "Volume could not be rendered - no attached buffer!");
1077 1078
          break;
        case kVLIErrAlloc:
1079
          vtkErrorMacro( << "Volume could not be rendered - not enough resources!" );
1080 1081
          break;
        default:
1082 1083 1084
          // Don't report the error - this volume just won't render
          vtkErrorMacro( << "Volume could not be rendered - unkown error!" );
          break;    
1085
        }
1086
      
1087 1088 1089
      return;
      }
    
1090 1091 1092 1093 1094 1095 1096 1097 1098
    size[0] = this->ImageBuffer->GetWidth();
    size[1] = this->ImageBuffer->GetHeight();
    
    unsigned int *outData = new unsigned int[size[0]*size[1]];
    
    status = this->ImageBuffer->Unload(outData,
                                       this->ImageBuffer->GetOutputLimits());
    
    if ( status != kVLIOK )
1099
      {
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
      switch (status)
        {
        case kVLIErrArgument:
          vtkErrorMacro("Image buffer could not be unloaded - invalid argument!");
          break;
        case kVLIErrAlloc:
          vtkErrorMacro("Image buffer could not be unloaded - not enough resources!");
          break;
        case kVLIErrInternal:
          vtkErrorMacro("Image buffer could not be unloaded - internal VLI error!");
          break;
        default:
          vtkErrorMacro("Image buffer could not be unloaded - unknown error!");
        }
1114 1115
      }
    
1116 1117 1118 1119
    // Render the image buffer we've been returned.
    this->RenderImageBuffer(ren, vol, size, outData);
    
    delete [] outData;
1120
    }
1121
  else
1122
    {
1123
    this->RenderBoundingBox(ren, vol);
1124 1125 1126
    }
}

1127 1128 1129 1130 1131 1132 1133
#if ((VTK_MAJOR_VERSION == 3)&&(VTK_MINOR_VERSION == 2))
void vtkVolumeProVP1000Mapper::ConvertCroppingRegionPlanesToVoxels()
{
  memcpy( this->VoxelCroppingRegionPlanes, this->CroppingRegionPlanes,
          sizeof ( this->VoxelCroppingRegionPlanes ) );
}
#endif
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 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390

VLIStatus vtkVolumeProVP1000Mapper::CheckSubSampling(const VLIVolume *inVolume,
                                                     const VLIContext *inContext,
                                                     int &outMinImageWidth,
                                                     int &outMinImageHeight)
{
  enum VGAxis
  {
    kU = 0,
    kV = 1,
    kW = 2
  };
  
  enum VGNeg
  {
    kNotNeg = 0,
    kIsNeg = 1
  };

  const double kEpsilonSubSample = 1.999;
  
  
  //////////////////////////////////////////////////////////////////////////
  //
  // 1) Initialize and calculate matrices: 
  //
  //////////////////////////////////////////////////////////////////////////
  
  VLIStatus status = kVLIOK;
  
  double depthNear, depthFar;
  int viewportMinX, viewportMinY, viewportWidth, viewportHeight;
  inContext->GetCamera().GetViewport(viewportMinX, viewportMinY,
                                     viewportWidth, viewportHeight);
  inContext->GetCamera().GetDepthRange(depthNear, depthFar);
  
  if (viewportWidth <=0 || viewportHeight <=0)
    {
    viewportWidth  = 3;
    viewportHeight = 3;
    viewportMinX = 0;
    viewportMinY = 0;
    status = kVLIErrCantSubsample;
    }
  
  //------------------------------------------------------
  // Calculate viewport matrix from viewport paramteres
  //------------------------------------------------------
  
  VLIMatrix viewportMatrix;
  viewportMatrix.Assign(
    (viewportWidth -1)/2.0, 0, 0, (viewportWidth -1)/2.0  + viewportMinX,
    0, (viewportHeight-1)/2.0, 0, (viewportHeight-1)/2.0  + viewportMinY,
    0, 0, (depthFar-depthNear)/2.0, (depthFar+depthNear)/2.0,
    0, 0, 0, 1.0);
  
  //------------------------------------------------------
  // Calculate viewport-viewmapping(projection)-CorrectedModelView matrix 
  //-------------------------------------------------------
  
  VLIMatrix projection = inContext->GetCamera().GetProjectionMatrix();
  VLIMatrix viewMatrix = inContext->GetCamera().GetViewMatrix();
  VLIMatrix model = inContext->GetCamera().GetModelMatrix();
  VLIMatrix correction = inVolume->GetCorrectionMatrix();
  
  VLIMatrix VP_VM_CRMVMatrix = 
    viewportMatrix * 
    inContext->GetCamera().GetProjectionMatrix() *
    inContext->GetCamera().GetViewMatrix() *
    inContext->GetCamera().GetModelMatrix() *
    inVolume->GetCorrectionMatrix();
  
  if (VP_VM_CRMVMatrix.IsSingular())
    {
    return kVLIErrTransform;
    }
  
  
  //////////////////////////////////////////////////////////////////////////
  //
  // 2) Calculate permutation matrix
  //   a) Choose primary axis to permuted space
  //   b) Decide the select and neg values in transform
  //   c) Construct permutation matrix considering min block
  //////////////////////////////////////////////////////////////////////////
  
  //------------------------------------------------------
  //   a) Choose primary axis to permuted space,
  //
  //      The Z axis of the permuted space  
  //      is one axis of object space that is 
  //      closest to the casting ray direction
  //------------------------------------------------------
  
  
  VLIVector4D view(0.0, 0.0, 1.0, 0.0);  // view vector in image space
  
  VLIMatrix VP_VM_CRMVInverse = VP_VM_CRMVMatrix.Inverse();
  
  VLIVector4D viewVectorInObjectSpace = (VP_VM_CRMVInverse * view).Normalize();
  
  double max = fabs (viewVectorInObjectSpace[0]);
  VGAxis primaryAxis = kU;
  
  if (fabs (viewVectorInObjectSpace[1]) > max) 
    {
    primaryAxis = kV;
    max = fabs(viewVectorInObjectSpace[1]);
    }
  
  if (fabs (viewVectorInObjectSpace[2]) > max) 
    {
    primaryAxis = kW;
    max = fabs(viewVectorInObjectSpace[2]);
    }
  
  //------------------------------------------------------
  //    b) Decide the select and neg values in transform
  //
  //       selectZ is the primary axis, negZ as its direction
  //
  //       selectX, selectY is chosen
  //       to keep the coordinate system order
  //------------------------------------------------------
  
  int dirSignOfViewVector[3]; // sign of du, dv, dw direction
  int i;
  for ( i = 0; i < 3 ; i++)
    {
    dirSignOfViewVector[i] =(viewVectorInObjectSpace[i] < 0 )? -1:1;
    }
  
  // even: 1, odd -1
  int even = dirSignOfViewVector[0] * dirSignOfViewVector[1]* 
    dirSignOfViewVector[2];
  
  
  int axisObj = primaryAxis; // axis of Object Space
  int negSign[3];
  
  // SelectZ, negZ
  VGAxis select[3];
  VGNeg neg[3];
  select[2] = primaryAxis; 
  neg[2] = (dirSignOfViewVector[axisObj] == 1)?kNotNeg:kIsNeg;
  negSign[2] = dirSignOfViewVector[axisObj];
  
  // SelectX, SelectY, negX, negY
  int axisP; // Axis of Permuted Space
  
  // The permuted axes are chosen to keep the same coordinate order
  // (right or left) as object space
  for ( i = 1; i < 3; i++)
    {
    axisP = (2+ i* even)%3;
    axisObj = (primaryAxis +i) %3;
    
    select[axisP] = (VGAxis)(axisObj);
    neg[axisP] = (dirSignOfViewVector[axisObj] == 1)?kNotNeg:kIsNeg;
    negSign[axisP] = dirSignOfViewVector[axisObj];
    }
  
  //-----------------------------------------------------------
  //    c) Construct permutation matrix considering mini block
  //------------------------------------------------------------
  
#define SELECT_AXIS(select, axisObj) ((select == axisObj)?1:0) 
#define PERMUTE(axisP,axisObj) negSign[axisP] * SELECT_AXIS(select[axisP], axisObj)
  
  // shift -1 if du, dv, dw < 0
#define SHIFT(index) ((negSign[index]==1)? 0:-1)
  VLIMatrix permutation;
  permutation.Assign(
    PERMUTE(0,kU), PERMUTE(0,kV),PERMUTE(0,kW), SHIFT(0),
    PERMUTE(1,kU), PERMUTE(1,kV),PERMUTE(1,kW), SHIFT(1),
    PERMUTE(2,kU), PERMUTE(2,kV),PERMUTE(2,kW), SHIFT(2),
    0, 0, 0, 1);
  
  //////////////////////////////////////////////////////////////////////////
  //  3) Calculate sample space increment registers using matrices
  //////////////////////////////////////////////////////////////////////////
  
  VLIMatrix VP_VM_CRMVPermuted = VP_VM_CRMVMatrix * permutation.Inverse();
  
  // 3.a) The 2x2 upper part of dI_DV Matrix is same in  dS_dV Matrix
  
  VLIMatrix dS_dVsubMatrix = VLIMatrix::Identity();
  
  dS_dVsubMatrix[0][0] = VP_VM_CRMVPermuted[0][0];
  dS_dVsubMatrix[0][1] = VP_VM_CRMVPermuted[0][1];
  dS_dVsubMatrix[1][0] = VP_VM_CRMVPermuted[1][0];
  dS_dVsubMatrix[1][1] = VP_VM_CRMVPermuted[1][1];
  
  VLIMatrix dV_dSsubMatrix  = dS_dVsubMatrix.Inverse();
  
  dV_dSsubMatrix[0][0] = fabs(dV_dSsubMatrix[0][0]);
  dV_dSsubMatrix[0][1] = fabs(dV_dSsubMatrix[0][1]);
  dV_dSsubMatrix[1][0] = fabs(dV_dSsubMatrix[1][0]);
  dV_dSsubMatrix[1][1] = fabs(dV_dSsubMatrix[1][1]);
  
  //////////////////////////////////////////////////////////
  //  A Scaling method that will
  //
  //  1) Change only the image size, (viewport)
  //
  //  2) keep the same permutation matrix
  //  
  //  3) keep valid DepthWarp Matrix
  //
  //  4) avoid sub sampling, so that
  // 
  //     VLIAbs(dXv_dXs) + VLIAbs(dXv_dYs) <=2
  //     VLIAbs(dYv_dXs) + VLIAbs(dYv_dYs) <=2
  //
  //     To conclude, get a scaleX, scaleY in imageSize
  // so that
  //     VLIAbs(dXv_dXs)/ScaleX+ VLIAbs(dXv_dYs)/ScaleY <=2
  //     VLIAbs(dXv_dYs)/ScaleX+ VLIAbs(dYv_dYs)/ScaleY <=2
  //
  //  Different ways to choose ScaleX, ScaleY to avoid sub Sampling
  //  We choose here when ScaleX == ScaleY, and most close to 
  //  ScaleX =1 , ScaleY =1
  //
  
  double dXvSampleMax= dV_dSsubMatrix[0][0] + dV_dSsubMatrix[0][1];
  double dYvSampleMax= dV_dSsubMatrix[1][0] + dV_dSsubMatrix[1][1];
  
  if (dXvSampleMax > 2.0 || dYvSampleMax > 2.0)
    {
    status = kVLIErrCantSubsample;
    }
  
  double viewportScale = dXvSampleMax > dYvSampleMax? dXvSampleMax:dYvSampleMax;
  
  viewportScale /= kEpsilonSubSample;
  //*************************************************
  //Solution I:
  //double dXvSampleMax= dV_dSsubMatrix[0][0] > dV_dSsubMatrix[1][0]? dV_dSsubMatrix[0][0]:dV_dSsubMatrix[1][0];
  //double dYvSampleMax= dV_dSsubMatrix[0][1] > dV_dSsubMatrix[1][1]? dV_dSsubMatrix[0][1]:dV_dSsubMatrix[1][1];
  //**************************************
  
  //*******************************
  //Solution II:
  /*Not proper to choose the interesection of the two equation!!!!
    VLIVector4D imageScale(2,2,0,0);
    dS_dVsubMatrix = dV_dSsubMatrix.Inverse();
    imageScale = dS_dVsubMatrix * imageScale;
    
    outMinImageWidth  = (int)ceil( (viewportWidth -1)/imageScale[0] +1);
    outMinImageHeight = (int)ceil( (viewportHeight-1)/imageScale[1] +1);*/
    
    // Instead of using scaling dXvSampleMax/2.0, using dZvSampleMax/kEpsionSubSample
    outMinImageWidth  = (int)ceil( double (viewportWidth -1)*viewportScale +1);
    outMinImageHeight = (int)ceil( double (viewportHeight-1)*viewportScale +1);
    
    return status;
}
Andy Cedilnik's avatar
Andy Cedilnik committed
1391 1392 1393 1394 1395 1396

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