void mitk::DoseImageVtkMapper2D::GenerateDataForRenderer( mitk::BaseRenderer *renderer )
{

  LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);

  mitk::Image *input = const_cast< mitk::Image * >( this->GetInput() );
  mitk::DataNode* datanode = this->GetDataNode();

  if ( input == NULL || input->IsInitialized() == false )
  {
    return;
  }

  //check if there is a valid worldGeometry
  const PlaneGeometry *worldGeometry = renderer->GetCurrentWorldPlaneGeometry();
  if( ( worldGeometry == NULL ) || ( !worldGeometry->IsValid() ) || ( !worldGeometry->HasReferenceGeometry() ))
  {
    return;
  }

  input->Update();

  // early out if there is no intersection of the current rendering geometry
  // and the geometry of the image that is to be rendered.
  if ( !RenderingGeometryIntersectsImage( worldGeometry, input->GetSlicedGeometry() ) )
  {
    // set image to NULL, to clear the texture in 3D, because
    // the latest image is used there if the plane is out of the geometry
    // see bug-13275
    localStorage->m_ReslicedImage = NULL;
    localStorage->m_Mapper->SetInputData( localStorage->m_EmptyPolyData );
    return;
  }

  //set main input for ExtractSliceFilter
  localStorage->m_Reslicer->SetInput(input);
  localStorage->m_Reslicer->SetWorldGeometry(worldGeometry);
  localStorage->m_Reslicer->SetTimeStep( this->GetTimestep() );

  //set the transformation of the image to adapt reslice axis
  localStorage->m_Reslicer->SetResliceTransformByGeometry( input->GetTimeGeometry()->GetGeometryForTimeStep( this->GetTimestep() ) );

  //is the geometry of the slice based on the input image or the worldgeometry?
  bool inPlaneResampleExtentByGeometry = false;
  datanode->GetBoolProperty("in plane resample extent by geometry", inPlaneResampleExtentByGeometry, renderer);
  localStorage->m_Reslicer->SetInPlaneResampleExtentByGeometry(inPlaneResampleExtentByGeometry);

  // Initialize the interpolation mode for resampling; switch to nearest
  // neighbor if the input image is too small.
  if ( (input->GetDimension() >= 3) && (input->GetDimension(2) > 1) )
  {
    VtkResliceInterpolationProperty *resliceInterpolationProperty;
    datanode->GetProperty(
      resliceInterpolationProperty, "reslice interpolation" );

    int interpolationMode = VTK_RESLICE_NEAREST;
    if ( resliceInterpolationProperty != NULL )
    {
      interpolationMode = resliceInterpolationProperty->GetInterpolation();
    }

    switch ( interpolationMode )
    {
    case VTK_RESLICE_NEAREST:
      localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_NEAREST);
      break;
    case VTK_RESLICE_LINEAR:
      localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_LINEAR);
      break;
    case VTK_RESLICE_CUBIC:
      localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_CUBIC);
      break;
    }
  }
  else
  {
    localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_NEAREST);
  }

  //set the vtk output property to true, makes sure that no unneeded mitk image convertion
  //is done.
  localStorage->m_Reslicer->SetVtkOutputRequest(true);

  //Thickslicing
  int thickSlicesMode = 0;
  int thickSlicesNum = 1;
  // Thick slices parameters
  if( input->GetPixelType().GetNumberOfComponents() == 1 ) // for now only single component are allowed
  {
    DataNode *dn=renderer->GetCurrentWorldPlaneGeometryNode();
    if(dn)
    {
      ResliceMethodProperty *resliceMethodEnumProperty=0;

      if( dn->GetProperty( resliceMethodEnumProperty, "reslice.thickslices" ) && resliceMethodEnumProperty )
        thickSlicesMode = resliceMethodEnumProperty->GetValueAsId();

      IntProperty *intProperty=0;
      if( dn->GetProperty( intProperty, "reslice.thickslices.num" ) && intProperty )
      {
        thickSlicesNum = intProperty->GetValue();
        if(thickSlicesNum < 1) thickSlicesNum=1;
        if(thickSlicesNum > 10) thickSlicesNum=10;
      }
    }
    else
    {
      MITK_WARN << "no associated widget plane data tree node found";
    }
  }

  const PlaneGeometry *planeGeometry = dynamic_cast< const PlaneGeometry * >( worldGeometry );

  if(thickSlicesMode > 0)
  {
    double dataZSpacing = 1.0;

    Vector3D normInIndex, normal;

    if ( planeGeometry != NULL ){
      normal = planeGeometry->GetNormal();
    }else{
      const mitk::AbstractTransformGeometry* abstractGeometry = dynamic_cast< const AbstractTransformGeometry * >(worldGeometry);
      if(abstractGeometry != NULL)
        normal = abstractGeometry->GetPlane()->GetNormal();
      else
        return; //no fitting geometry set
    }
    normal.Normalize();

    input->GetTimeGeometry()->GetGeometryForTimeStep( this->GetTimestep() )->WorldToIndex( normal, normInIndex );

    dataZSpacing = 1.0 / normInIndex.GetNorm();

    localStorage->m_Reslicer->SetOutputDimensionality( 3 );
    localStorage->m_Reslicer->SetOutputSpacingZDirection(dataZSpacing);
    localStorage->m_Reslicer->SetOutputExtentZDirection( -thickSlicesNum, 0+thickSlicesNum );

    // Do the reslicing. Modified() is called to make sure that the reslicer is
    // executed even though the input geometry information did not change; this
    // is necessary when the input /em data, but not the /em geometry changes.
    localStorage->m_TSFilter->SetThickSliceMode( thickSlicesMode-1 );
    localStorage->m_TSFilter->SetInputData( localStorage->m_Reslicer->GetVtkOutput() );

    //vtkFilter=>mitkFilter=>vtkFilter update mechanism will fail without calling manually
    localStorage->m_Reslicer->Modified();
    localStorage->m_Reslicer->Update();

    localStorage->m_TSFilter->Modified();
    localStorage->m_TSFilter->Update();
    localStorage->m_ReslicedImage = localStorage->m_TSFilter->GetOutput();
  }
  else
  {
    //this is needed when thick mode was enable bevore. These variable have to be reset to default values
    localStorage->m_Reslicer->SetOutputDimensionality( 2 );
    localStorage->m_Reslicer->SetOutputSpacingZDirection(1.0);
    localStorage->m_Reslicer->SetOutputExtentZDirection( 0, 0 );


    localStorage->m_Reslicer->Modified();
    //start the pipeline with updating the largest possible, needed if the geometry of the input has changed
    localStorage->m_Reslicer->UpdateLargestPossibleRegion();
    localStorage->m_ReslicedImage = localStorage->m_Reslicer->GetVtkOutput();
  }

  // Bounds information for reslicing (only reuqired if reference geometry
  // is present)
  //this used for generating a vtkPLaneSource with the right size
  double sliceBounds[6];
  for ( int i = 0; i < 6; ++i )
  {
    sliceBounds[i] = 0.0;
  }
  localStorage->m_Reslicer->GetClippedPlaneBounds(sliceBounds);

  //get the spacing of the slice
  localStorage->m_mmPerPixel = localStorage->m_Reslicer->GetOutputSpacing();

  // calculate minimum bounding rect of IMAGE in texture
  {
    double textureClippingBounds[6];
    for ( int i = 0; i < 6; ++i )
    {
      textureClippingBounds[i] = 0.0;
    }
    // Calculate the actual bounds of the transformed plane clipped by the
    // dataset bounding box; this is required for drawing the texture at the
    // correct position during 3D mapping.
    mitk::PlaneClipping::CalculateClippedPlaneBounds( input->GetGeometry(), planeGeometry, textureClippingBounds );

    textureClippingBounds[0] = static_cast< int >( textureClippingBounds[0] / localStorage->m_mmPerPixel[0] + 0.5 );
    textureClippingBounds[1] = static_cast< int >( textureClippingBounds[1] / localStorage->m_mmPerPixel[0] + 0.5 );
    textureClippingBounds[2] = static_cast< int >( textureClippingBounds[2] / localStorage->m_mmPerPixel[1] + 0.5 );
    textureClippingBounds[3] = static_cast< int >( textureClippingBounds[3] / localStorage->m_mmPerPixel[1] + 0.5 );

    //clipping bounds for cutting the image
    localStorage->m_LevelWindowFilter->SetClippingBounds(textureClippingBounds);
  }

  //get the number of scalar components to distinguish between different image types
  int numberOfComponents = localStorage->m_ReslicedImage->GetNumberOfScalarComponents();
  //get the showIsoLines property
  bool showIsoLines = false;
  datanode->GetBoolProperty( "dose.showIsoLines", showIsoLines, renderer );

  if(showIsoLines) //contour rendering
  {
    //generate contours/outlines
    localStorage->m_OutlinePolyData = CreateOutlinePolyData(renderer);

    float binaryOutlineWidth(1.0);
    if ( datanode->GetFloatProperty( "outline width", binaryOutlineWidth, renderer ) )
    {
      if ( localStorage->m_Actors->GetNumberOfPaths() > 1 )
      {
        float binaryOutlineShadowWidth(1.5);
        datanode->GetFloatProperty( "outline shadow width", binaryOutlineShadowWidth, renderer );

        dynamic_cast<vtkActor*>(localStorage->m_Actors->GetParts()->GetItemAsObject(0))
          ->GetProperty()->SetLineWidth( binaryOutlineWidth * binaryOutlineShadowWidth );
      }

      localStorage->m_Actor->GetProperty()->SetLineWidth( binaryOutlineWidth );
    }
  }
  else
  {
    localStorage->m_ReslicedImage = NULL;
    localStorage->m_Mapper->SetInputData( localStorage->m_EmptyPolyData );
    return;
  }

  this->ApplyOpacity( renderer );
  this->ApplyRenderingMode(renderer);

  // do not use a VTK lookup table (we do that ourselves in m_LevelWindowFilter)
  localStorage->m_Texture->MapColorScalarsThroughLookupTableOff();

  int displayedComponent = 0;

  if (datanode->GetIntProperty("Image.Displayed Component", displayedComponent, renderer) && numberOfComponents > 1)
  {
    localStorage->m_VectorComponentExtractor->SetComponents(displayedComponent);
    localStorage->m_VectorComponentExtractor->SetInputData(localStorage->m_ReslicedImage);

    localStorage->m_LevelWindowFilter->SetInputConnection(localStorage->m_VectorComponentExtractor->GetOutputPort(0));
  }
  else
  {
    //connect the input with the levelwindow filter
    localStorage->m_LevelWindowFilter->SetInputData(localStorage->m_ReslicedImage);
  }

  // check for texture interpolation property
  bool textureInterpolation = false;
  GetDataNode()->GetBoolProperty( "texture interpolation", textureInterpolation, renderer );

  //set the interpolation modus according to the property
  localStorage->m_Texture->SetInterpolate(textureInterpolation);

  // connect the texture with the output of the levelwindow filter
  localStorage->m_Texture->SetInputConnection(localStorage->m_LevelWindowFilter->GetOutputPort());

  this->TransformActor( renderer );

  vtkActor* contourShadowActor = dynamic_cast<vtkActor*> (localStorage->m_Actors->GetParts()->GetItemAsObject(0));

  if(showIsoLines) //connect the mapper with the polyData which contains the lines
  {
    //We need the contour for the binary outline property as actor
    localStorage->m_Mapper->SetInputData(localStorage->m_OutlinePolyData);
    localStorage->m_Actor->SetTexture(NULL); //no texture for contours

    bool binaryOutlineShadow( false );
    datanode->GetBoolProperty( "outline binary shadow", binaryOutlineShadow, renderer );

    if ( binaryOutlineShadow )
      contourShadowActor->SetVisibility( true );
    else
      contourShadowActor->SetVisibility( false );
  }
  else
  { //Connect the mapper with the input texture. This is the standard case.
    //setup the textured plane
    this->GeneratePlane( renderer, sliceBounds );
    //set the plane as input for the mapper
    localStorage->m_Mapper->SetInputConnection(localStorage->m_Plane->GetOutputPort());
    //set the texture for the actor

    localStorage->m_Actor->SetTexture(localStorage->m_Texture);
    contourShadowActor->SetVisibility( false );
  }

  // We have been modified => save this for next Update()
  localStorage->m_LastUpdateTime.Modified();
}
Ejemplo n.º 2
0
bool mitk::PointSetDataInteractor::InitMove(StateMachineAction*, InteractionEvent*)
{
  GetDataNode()->SetProperty("contourcolor", ColorProperty::New(1.0, 1.0, 1.0));
  return true;
}
void mitk::UnstructuredGridMapper2D::Paint( mitk::BaseRenderer* renderer )
{
  bool visible = true;
  GetDataNode()->GetVisibility(visible, renderer, "visible");
  if(!visible) return;

  vtkLinearTransform * vtktransform = GetDataNode()->GetVtkTransform();
  vtkLinearTransform * inversetransform = vtktransform->GetLinearInverse();

  PlaneGeometry::ConstPointer worldGeometry = renderer->GetCurrentWorldPlaneGeometry();
  PlaneGeometry::ConstPointer worldPlaneGeometry = dynamic_cast<const PlaneGeometry*>( worldGeometry.GetPointer() );

  Point3D point;
  Vector3D normal;

  if(worldPlaneGeometry.IsNotNull())
  {
    // set up vtkPlane according to worldGeometry
    point=worldPlaneGeometry->GetOrigin();
    normal=worldPlaneGeometry->GetNormal(); normal.Normalize();
    m_Plane->SetTransform((vtkAbstractTransform*)NULL);
  }
  else
  {
    //@FIXME: does not work correctly. Does m_Plane->SetTransform really transforms a "plane plane" into a "curved plane"?
    return;
    AbstractTransformGeometry::ConstPointer worldAbstractGeometry = dynamic_cast<const AbstractTransformGeometry*>(renderer->GetCurrentWorldPlaneGeometry());
    if(worldAbstractGeometry.IsNotNull())
    {
      // set up vtkPlane according to worldGeometry
      point=const_cast<mitk::BoundingBox*>(worldAbstractGeometry->GetParametricBoundingBox())->GetMinimum();
      FillVector3D(normal, 0, 0, 1);
      m_Plane->SetTransform(worldAbstractGeometry->GetVtkAbstractTransform()->GetInverse());
    }
    else
      return;
  }

  double vp[ 3 ], vnormal[ 3 ];

  vnl2vtk(point.GetVnlVector(), vp);
  vnl2vtk(normal.GetVnlVector(), vnormal);

  //normally, we would need to transform the surface and cut the transformed surface with the cutter.
  //This might be quite slow. Thus, the idea is, to perform an inverse transform of the plane instead.
  //@todo It probably does not work for scaling operations yet:scaling operations have to be
  //dealed with after the cut is performed by scaling the contour.
  inversetransform->TransformPoint( vp, vp );
  inversetransform->TransformNormalAtPoint( vp, vnormal, vnormal );

  m_Plane->SetOrigin( vp );
  m_Plane->SetNormal( vnormal );

  // set data into cutter
  m_Slicer->SetInputData( m_VtkPointSet );
  //    m_Cutter->GenerateCutScalarsOff();
  //    m_Cutter->SetSortByToSortByCell();

  // calculate the cut
  m_Slicer->Update();

  //apply color and opacity read from the PropertyList
  ApplyColorAndOpacityProperties( renderer );

  // traverse the cut contour
  vtkPolyData * contour = m_Slicer->GetOutput();

  vtkPoints *vpoints = contour->GetPoints();
  vtkCellArray *vlines = contour->GetLines();
  vtkCellArray *vpolys = contour->GetPolys();
  vtkPointData *vpointdata = contour->GetPointData();
  vtkDataArray* vscalars = vpointdata->GetScalars();

  vtkCellData *vcelldata = contour->GetCellData();
  vtkDataArray* vcellscalars = vcelldata->GetScalars();

  const int numberOfLines = contour->GetNumberOfLines();
  const int numberOfPolys = contour->GetNumberOfPolys();

  const bool useCellData = m_ScalarMode->GetVtkScalarMode() == VTK_SCALAR_MODE_DEFAULT ||
      m_ScalarMode->GetVtkScalarMode() == VTK_SCALAR_MODE_USE_CELL_DATA;
  const bool usePointData = m_ScalarMode->GetVtkScalarMode() == VTK_SCALAR_MODE_USE_POINT_DATA;

  Point3D p;
  Point2D p2d;

  vlines->InitTraversal();
  vpolys->InitTraversal();

  mitk::Color outlineColor = m_Color->GetColor();

  glLineWidth((float)m_LineWidth->GetValue());

  for (int i = 0;i < numberOfLines;++i )
  {
    vtkIdType *cell(0);
    vtkIdType cellSize(0);

    vlines->GetNextCell( cellSize, cell );

    float rgba[4] = {outlineColor[0], outlineColor[1], outlineColor[2], 1.0f};
    if (m_ScalarVisibility->GetValue() && vcellscalars)
    {
      if ( useCellData )
      {  // color each cell according to cell data
        double scalar = vcellscalars->GetComponent( i, 0 );
        double rgb[3] = { 1.0f, 1.0f, 1.0f };
        m_ScalarsToColors->GetColor(scalar, rgb);
        rgba[0] = (float)rgb[0];
        rgba[1] = (float)rgb[1];
        rgba[2] = (float)rgb[2];
        rgba[3] = (float)m_ScalarsToOpacity->GetValue(scalar);
      }
      else if ( usePointData )
      {
        double scalar = vscalars->GetComponent( i, 0 );
        double rgb[3] = { 1.0f, 1.0f, 1.0f };
        m_ScalarsToColors->GetColor(scalar, rgb);
        rgba[0] = (float)rgb[0];
        rgba[1] = (float)rgb[1];
        rgba[2] = (float)rgb[2];
        rgba[3] = (float)m_ScalarsToOpacity->GetValue(scalar);
      }
    }

    glColor4fv( rgba );

    glBegin ( GL_LINE_LOOP );
    for ( int j = 0;j < cellSize;++j )
    {
      vpoints->GetPoint( cell[ j ], vp );
      //take transformation via vtktransform into account
      vtktransform->TransformPoint( vp, vp );

      vtk2itk( vp, p );

      //convert 3D point (in mm) to display coordinates (units )
      renderer->WorldToDisplay( p, p2d );

      //convert display coordinates ( (0,0) is top-left ) in GL coordinates ( (0,0) is bottom-left )
      //p2d[1]=toGL-p2d[1];

      //add the current vertex to the line
      glVertex2f( p2d[0], p2d[1] );
    }
    glEnd ();

  }

  bool polyOutline = m_Outline->GetValue();
  bool scalarVisibility = m_ScalarVisibility->GetValue();

  // cache the transformed points
  // a fixed size array is way faster than 'new'
  // slices through 3d cells usually do not generated
  // polygons with more than 6 vertices
  const int maxPolySize = 10;
  Point2D* cachedPoints = new Point2D[maxPolySize*numberOfPolys];

  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  // only draw polygons if there are cell scalars
  // or the outline property is set to true
  if (scalarVisibility && vcellscalars)
  {
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

    for (int i = 0;i < numberOfPolys;++i )
    {
      vtkIdType *cell(0);
      vtkIdType cellSize(0);

      vpolys->GetNextCell( cellSize, cell );

      float rgba[4] = {1.0f, 1.0f, 1.0f, 0};
      if (scalarVisibility && vcellscalars)
      {
        if ( useCellData )
        {  // color each cell according to cell data
          double scalar = vcellscalars->GetComponent( i+numberOfLines, 0 );
          double rgb[3] = { 1.0f, 1.0f, 1.0f };
          m_ScalarsToColors->GetColor(scalar, rgb);
          rgba[0] = (float)rgb[0];
          rgba[1] = (float)rgb[1];
          rgba[2] = (float)rgb[2];
          rgba[3] = (float)m_ScalarsToOpacity->GetValue(scalar);
        }
        else if ( usePointData )
        {
          double scalar = vscalars->GetComponent( i, 0 );
          double rgb[3] = { 1.0f, 1.0f, 1.0f };
          m_ScalarsToColors->GetColor(scalar, rgb);
          rgba[0] = (float)rgb[0];
          rgba[1] = (float)rgb[1];
          rgba[2] = (float)rgb[2];
          rgba[3] = (float)m_ScalarsToOpacity->GetValue(scalar);
        }
      }
      glColor4fv( rgba );

      glBegin( GL_POLYGON );
      for (int j = 0; j < cellSize; ++j)
      {
        vpoints->GetPoint( cell[ j ], vp );
        //take transformation via vtktransform into account
        vtktransform->TransformPoint( vp, vp );

        vtk2itk( vp, p );

        //convert 3D point (in mm) to display coordinates (units )
        renderer->WorldToDisplay( p, p2d );

        //convert display coordinates ( (0,0) is top-left ) in GL coordinates ( (0,0) is bottom-left )
        //p2d[1]=toGL-p2d[1];

        cachedPoints[i*10+j][0] = p2d[0];
        cachedPoints[i*10+j][1] = p2d[1];

        //add the current vertex to the line
        glVertex2f( p2d[0], p2d[1] );
      }
      glEnd();
    }

    if (polyOutline)
    {
      vpolys->InitTraversal();

      glColor4f(outlineColor[0], outlineColor[1], outlineColor[2], 1.0f);
      glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
      for (int i = 0;i < numberOfPolys;++i)
      {
        vtkIdType *cell(0);
        vtkIdType cellSize(0);

        vpolys->GetNextCell( cellSize, cell );

        glBegin( GL_POLYGON );
        //glPolygonOffset(1.0, 1.0);
        for (int j = 0; j < cellSize; ++j)
        {
          //add the current vertex to the line
          glVertex2f( cachedPoints[i*10+j][0], cachedPoints[i*10+j][1] );
        }
        glEnd();
      }
    }
  }
  glDisable(GL_BLEND);
  delete[] cachedPoints;
}
Ejemplo n.º 4
0
void mitk::VolumeDataVtkMapper3D::UpdateTransferFunctions( mitk::BaseRenderer *renderer )
{
  vtkPiecewiseFunction *opacityTransferFunction = NULL;
  vtkPiecewiseFunction *gradientTransferFunction = NULL;
  vtkColorTransferFunction *colorTransferFunction = NULL;

  mitk::LookupTableProperty::Pointer lookupTableProp;
  lookupTableProp = dynamic_cast<mitk::LookupTableProperty*>(this->GetDataNode()->GetProperty("LookupTable"));
  mitk::TransferFunctionProperty::Pointer transferFunctionProp = dynamic_cast<mitk::TransferFunctionProperty*>(this->GetDataNode()->GetProperty("TransferFunction"));

  if ( transferFunctionProp.IsNotNull() )   {

    opacityTransferFunction = transferFunctionProp->GetValue()->GetScalarOpacityFunction();
    gradientTransferFunction = transferFunctionProp->GetValue()->GetGradientOpacityFunction();
    colorTransferFunction = transferFunctionProp->GetValue()->GetColorTransferFunction();
  }
  else if (lookupTableProp.IsNotNull() )
  {
    lookupTableProp->GetLookupTable()->CreateOpacityTransferFunction(opacityTransferFunction);
    opacityTransferFunction->ClampingOn();
    lookupTableProp->GetLookupTable()->CreateGradientTransferFunction(gradientTransferFunction);
    gradientTransferFunction->ClampingOn();
    lookupTableProp->GetLookupTable()->CreateColorTransferFunction(colorTransferFunction);
    colorTransferFunction->ClampingOn();
  }
  else
  {
    opacityTransferFunction = m_DefaultOpacityTransferFunction;
    gradientTransferFunction = m_DefaultGradientTransferFunction;
    colorTransferFunction = m_DefaultColorTransferFunction;

    float rgb[3]={1.0f,1.0f,1.0f};
    // check for color prop and use it for rendering if it exists
    if(GetDataNode()->GetColor(rgb, renderer, "color"))
    {
      colorTransferFunction->AddRGBPoint( 0.0, 0.0, 0.0, 0.0 );
      colorTransferFunction->AddRGBPoint( 127.5, rgb[0], rgb[1], rgb[2] );
      colorTransferFunction->AddRGBPoint( 255.0, rgb[0], rgb[1], rgb[2] );
    }
  }

  if (this->m_Mask)
  {
    opacityTransferFunction->AddPoint(0xffff, 0.0);
  }

  m_VolumePropertyLow->SetColor( colorTransferFunction );
  m_VolumePropertyLow->SetScalarOpacity( opacityTransferFunction );
  m_VolumePropertyLow->SetGradientOpacity( gradientTransferFunction );
  m_VolumePropertyLow->SetInterpolationTypeToNearest();

  m_VolumePropertyMed->SetColor( colorTransferFunction );
  m_VolumePropertyMed->SetScalarOpacity( opacityTransferFunction );
  m_VolumePropertyMed->SetGradientOpacity( gradientTransferFunction );
  m_VolumePropertyMed->SetInterpolationTypeToNearest();

  m_VolumePropertyHigh->SetColor( colorTransferFunction );
  m_VolumePropertyHigh->SetScalarOpacity( opacityTransferFunction );
  m_VolumePropertyHigh->SetGradientOpacity( gradientTransferFunction );
  m_VolumePropertyHigh->SetInterpolationTypeToLinear();
}
Ejemplo n.º 5
0
void mitk::PointSetVtkMapper3D::GenerateDataForRenderer(mitk::BaseRenderer *renderer)
{
  bool visible = true;
  GetDataNode()->GetVisibility(visible, renderer, "visible");
  if (!visible)
  {
    m_UnselectedActor->VisibilityOff();
    m_SelectedActor->VisibilityOff();
    m_ContourActor->VisibilityOff();
    return;
  }

  // create new vtk render objects (e.g. sphere for a point)

  SetVtkMapperImmediateModeRendering(m_VtkSelectedPolyDataMapper);
  SetVtkMapperImmediateModeRendering(m_VtkUnselectedPolyDataMapper);

  BaseLocalStorage *ls = m_LSH.GetLocalStorage(renderer);
  bool needGenerateData = ls->IsGenerateDataRequired(renderer, this, GetDataNode());

  if (!needGenerateData)
  {
    mitk::FloatProperty *pointSizeProp =
      dynamic_cast<mitk::FloatProperty *>(this->GetDataNode()->GetProperty("pointsize"));
    mitk::FloatProperty *contourSizeProp =
      dynamic_cast<mitk::FloatProperty *>(this->GetDataNode()->GetProperty("contoursize"));

    bool useVertexRendering = false;
    this->GetDataNode()->GetBoolProperty("Vertex Rendering", useVertexRendering);

    // only create new vtk render objects if property values were changed
    if (pointSizeProp && m_PointSize != pointSizeProp->GetValue())
      needGenerateData = true;
    if (contourSizeProp && m_ContourRadius != contourSizeProp->GetValue())
      needGenerateData = true;

    // when vertex rendering is enabled the pointset is always
    // drawn with opengl, thus we leave needGenerateData always false
    if (useVertexRendering && m_VertexRendering != useVertexRendering)
    {
      needGenerateData = false;
      m_VertexRendering = true;
    }
    else if (!useVertexRendering && m_VertexRendering)
    {
      m_VertexRendering = false;
      needGenerateData = true;
    }
  }

  if (needGenerateData)
  {
    this->CreateVTKRenderObjects();
    ls->UpdateGenerateDataTime();
  }

  this->ApplyAllProperties(renderer, m_ContourActor);

  bool showPoints = true;
  this->GetDataNode()->GetBoolProperty("show points", showPoints);

  m_UnselectedActor->SetVisibility(showPoints && !m_VertexRendering);
  m_SelectedActor->SetVisibility(showPoints && !m_VertexRendering);

  if (false && dynamic_cast<mitk::FloatProperty *>(this->GetDataNode()->GetProperty("opacity")) != nullptr)
  {
    mitk::FloatProperty::Pointer pointOpacity =
      dynamic_cast<mitk::FloatProperty *>(this->GetDataNode()->GetProperty("opacity"));
    float opacity = pointOpacity->GetValue();
    m_ContourActor->GetProperty()->SetOpacity(opacity);
    m_UnselectedActor->GetProperty()->SetOpacity(opacity);
    m_SelectedActor->GetProperty()->SetOpacity(opacity);
  }

  bool showContour = false;
  this->GetDataNode()->GetBoolProperty("show contour", showContour);
  m_ContourActor->SetVisibility(showContour);

  // use vertex rendering
  if (m_VertexRendering)
  {
    VertexRendering();
    ls->UpdateGenerateDataTime();
  }
}
Ejemplo n.º 6
0
bool mitk::GPUVolumeMapper3D::IsRAYEnabled( mitk::BaseRenderer * renderer )
{
  LocalStorage *ls = m_LSH.GetLocalStorage(renderer);
  bool value = false;
  return ls->m_raySupported && GetDataNode()->GetBoolProperty("volumerendering.useray",value,renderer) && value;
}
const mitk::UnstructuredGrid* mitk::UnstructuredGridVtkMapper3D::GetInput()
{
  return static_cast<const mitk::UnstructuredGrid * > ( GetDataNode()->GetData() );
}
Ejemplo n.º 8
0
const mitk::ContourModelSet* mitk::ContourModelSetMapper3D::GetInput( void )
{
  //convient way to get the data from the dataNode
  return static_cast< const mitk::ContourModelSet * >( GetDataNode()->GetData() );
}
Ejemplo n.º 9
0
mitk::FiberBundleX* mitk::FiberBundleXMapper2D::GetInput()
{
    return dynamic_cast< mitk::FiberBundleX * > ( GetDataNode()->GetData() );
}
void mitk::PointSetVtkMapper2D::CreateVTKRenderObjects(mitk::BaseRenderer* renderer)
{
  LocalStorage *ls = m_LSH.GetLocalStorage(renderer);

  unsigned i = 0;

  // The vtk text actors need to be removed manually from the propassembly
  // since the same vtk text actors are not overwriten within this function,
  // but new actors are added to the propassembly each time this function is executed.
  // Thus, the actors from the last call must be removed in the beginning.
  for(i=0; i< ls->m_VtkTextLabelActors.size(); i++)
  {
    if(ls->m_PropAssembly->GetParts()->IsItemPresent(ls->m_VtkTextLabelActors.at(i)))
      ls->m_PropAssembly->RemovePart(ls->m_VtkTextLabelActors.at(i));
  }

  for(i=0; i< ls->m_VtkTextDistanceActors.size(); i++)
  {
    if(ls->m_PropAssembly->GetParts()->IsItemPresent(ls->m_VtkTextDistanceActors.at(i)))
      ls->m_PropAssembly->RemovePart(ls->m_VtkTextDistanceActors.at(i));
  }

  for(i=0; i< ls->m_VtkTextAngleActors.size(); i++)
  {
    if(ls->m_PropAssembly->GetParts()->IsItemPresent(ls->m_VtkTextAngleActors.at(i)))
      ls->m_PropAssembly->RemovePart(ls->m_VtkTextAngleActors.at(i));
  }

  // initialize polydata here, otherwise we have update problems when
  // executing this function again
  ls->m_VtkUnselectedPointListPolyData = vtkSmartPointer<vtkPolyData>::New();
  ls->m_VtkSelectedPointListPolyData = vtkSmartPointer <vtkPolyData>::New();
  ls->m_VtkContourPolyData = vtkSmartPointer<vtkPolyData>::New();

  // get input point set and update the PointSet
  mitk::PointSet::Pointer input  = const_cast<mitk::PointSet*>(this->GetInput());

  // only update the input data, if the property tells us to
  bool update = true;
  this->GetDataNode()->GetBoolProperty("updateDataOnRender", update);
  if (update == true)
    input->Update();

  int timestep = this->GetTimestep();
  mitk::PointSet::DataType::Pointer itkPointSet = input->GetPointSet( timestep );

  if ( itkPointSet.GetPointer() == NULL)
  {
    ls->m_PropAssembly->VisibilityOff();
    return;
  }

  //iterator for point set
  mitk::PointSet::PointsContainer::Iterator pointsIter = itkPointSet->GetPoints()->Begin();

  // PointDataContainer has additional information to each point, e.g. whether
  // it is selected or not
  mitk::PointSet::PointDataContainer::Iterator pointDataIter;
  pointDataIter = itkPointSet->GetPointData()->Begin();

  //check if the list for the PointDataContainer is the same size as the PointsContainer.
  //If not, then the points were inserted manually and can not be visualized according to the PointData (selected/unselected)
  bool pointDataBroken = (itkPointSet->GetPointData()->Size() != itkPointSet->GetPoints()->Size());

  if( itkPointSet->GetPointData()->size() == 0 || pointDataBroken)
  {
    ls->m_PropAssembly->VisibilityOff();
    return;
  }

  ls->m_PropAssembly->VisibilityOn();

  // empty point sets, cellarrays, scalars
  ls->m_UnselectedPoints->Reset();
  ls->m_SelectedPoints->Reset();

  ls->m_ContourPoints->Reset();
  ls->m_ContourLines->Reset();

  ls->m_UnselectedScales->Reset();
  ls->m_SelectedScales->Reset();

  ls->m_DistancesBetweenPoints->Reset();

  ls->m_VtkTextLabelActors.clear();
  ls->m_VtkTextDistanceActors.clear();
  ls->m_VtkTextAngleActors.clear();

  ls->m_UnselectedScales->SetNumberOfComponents(3);
  ls->m_SelectedScales->SetNumberOfComponents(3);

  int NumberContourPoints = 0;
  bool pointsOnSameSideOfPlane = false;

  const int text2dDistance = 10;

  // initialize points with a random start value

  // current point in point set
  itk::Point<ScalarType> point = pointsIter->Value();

  mitk::Point3D p = point;              // currently visited point
  mitk::Point3D lastP = point;          // last visited point (predecessor in point set of "point")
  mitk::Vector3D vec;                   // p - lastP
  mitk::Vector3D lastVec;               // lastP - point before lastP
  vec.Fill(0.0);
  lastVec.Fill(0.0);

  mitk::Point3D projected_p = point;     // p projected on viewplane

  mitk::Point2D pt2d;
  pt2d[0] = point[0];                    // projected_p in display coordinates
  pt2d[1] = point[1];
  mitk::Point2D lastPt2d = pt2d;         // last projected_p in display coordinates (predecessor in point set of "pt2d")
  mitk::Point2D preLastPt2d = pt2d ;     // projected_p in display coordinates before lastPt2

  mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry();
  const mitk::PlaneGeometry* geo2D = renderer->GetCurrentWorldPlaneGeometry();

  vtkLinearTransform* dataNodeTransform = input->GetGeometry()->GetVtkTransform();

  int count = 0;

  for (pointsIter=itkPointSet->GetPoints()->Begin();
    pointsIter!=itkPointSet->GetPoints()->End();
    pointsIter++)
  {
    lastP = p; // valid for number of points count > 0
    preLastPt2d = lastPt2d; // valid only for count > 1
    lastPt2d = pt2d;  // valid for number of points count > 0

    lastVec = vec;    // valid only for counter > 1

    // get current point in point set
    point = pointsIter->Value();

    // transform point
    {
      float vtkp[3];
      itk2vtk(point, vtkp);
      dataNodeTransform->TransformPoint(vtkp, vtkp);
      vtk2itk(vtkp,point);
    }

    p[0] = point[0];
    p[1] = point[1];
    p[2] = point[2];

    displayGeometry->Project(p, projected_p);
    displayGeometry->Map(projected_p, pt2d);
    displayGeometry->WorldToDisplay(pt2d, pt2d);

    vec = p-lastP;    // valid only for counter > 0

    // compute distance to current plane
    float diff = geo2D->Distance(point);
    diff = diff * diff;

    //draw markers on slices a certain distance away from the points
    //location according to the tolerance threshold (m_DistanceToPlane)
    if(diff < m_DistanceToPlane)
    {
      // is point selected or not?
      if (pointDataIter->Value().selected)
      {
        ls->m_SelectedPoints->InsertNextPoint(point[0],point[1],point[2]);
        // point is scaled according to its distance to the plane
        ls->m_SelectedScales->InsertNextTuple3(m_Point2DSize - (2*diff),0,0);
      }
      else
      {
        ls->m_UnselectedPoints->InsertNextPoint(point[0],point[1],point[2]);
        // point is scaled according to its distance to the plane
        ls->m_UnselectedScales->InsertNextTuple3(m_Point2DSize - (2*diff),0,0);
      }

      //---- LABEL -----//
      //paint label for each point if available
      if (dynamic_cast<mitk::StringProperty *>(this->GetDataNode()->GetProperty("label")) != NULL)
      {
        const char * pointLabel = dynamic_cast<mitk::StringProperty *>(
          this->GetDataNode()->GetProperty("label"))->GetValue();
        std::string l = pointLabel;
        if (input->GetSize()>1)
        {
          std::stringstream ss;
          ss << pointsIter->Index();
          l.append(ss.str());
        }

        ls->m_VtkTextActor = vtkSmartPointer<vtkTextActor>::New();

        ls->m_VtkTextActor->SetPosition(pt2d[0] + text2dDistance, pt2d[1] + text2dDistance);
        ls->m_VtkTextActor->SetInput(l.c_str());
        ls->m_VtkTextActor->GetTextProperty()->SetOpacity( 100 );

        float unselectedColor[4] = {1.0, 1.0, 0.0, 1.0};

        //check if there is a color property
        GetDataNode()->GetColor(unselectedColor);

        ls->m_VtkTextActor->GetTextProperty()->SetColor(unselectedColor[0], unselectedColor[1], unselectedColor[2]);

        ls->m_VtkTextLabelActors.push_back(ls->m_VtkTextActor);
      }
    }

    // draw contour, distance text and angle text in render window

    // lines between points, which intersect the current plane, are drawn
    if( m_ShowContour && count > 0 )
    {
      ScalarType distance =    displayGeometry->GetWorldGeometry()->SignedDistance(point);
      ScalarType lastDistance =    displayGeometry->GetWorldGeometry()->SignedDistance(lastP);

      pointsOnSameSideOfPlane = (distance * lastDistance) > 0.5;

      // Points must be on different side of plane in order to draw a contour.
      // If "show distant lines" is enabled this condition is disregarded.
      if ( !pointsOnSameSideOfPlane || m_ShowDistantLines)
      {
        vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New();

        ls->m_ContourPoints->InsertNextPoint(lastP[0],lastP[1],lastP[2]);
        line->GetPointIds()->SetId(0, NumberContourPoints);
        NumberContourPoints++;

        ls->m_ContourPoints->InsertNextPoint(point[0], point[1], point[2]);
        line->GetPointIds()->SetId(1, NumberContourPoints);
        NumberContourPoints++;

        ls->m_ContourLines->InsertNextCell(line);

        if(m_ShowDistances) // calculate and print distance between adjacent points
        {
          float distancePoints = point.EuclideanDistanceTo(lastP);

          std::stringstream buffer;
          buffer<<std::fixed <<std::setprecision(m_DistancesDecimalDigits)<<distancePoints<<" mm";

          // compute desired display position of text
          Vector2D vec2d = pt2d-lastPt2d;
          makePerpendicularVector2D(vec2d, vec2d); // text is rendered within text2dDistance perpendicular to current line
          Vector2D pos2d = (lastPt2d.GetVectorFromOrigin() + pt2d.GetVectorFromOrigin() ) * 0.5 + vec2d * text2dDistance;

          ls->m_VtkTextActor = vtkSmartPointer<vtkTextActor>::New();

          ls->m_VtkTextActor->SetPosition(pos2d[0],pos2d[1]);
          ls->m_VtkTextActor->SetInput(buffer.str().c_str());
          ls->m_VtkTextActor->GetTextProperty()->SetColor(0.0, 1.0, 0.0);

          ls->m_VtkTextDistanceActors.push_back(ls->m_VtkTextActor);
        }

        if(m_ShowAngles && count > 1) // calculate and print angle between connected lines
        {
          std::stringstream buffer;
          buffer << angle(vec.GetVnlVector(), -lastVec.GetVnlVector())*180/vnl_math::pi << "°";

          //compute desired display position of text
          Vector2D vec2d = pt2d-lastPt2d;             // first arm enclosing the angle
          vec2d.Normalize();
          Vector2D lastVec2d = lastPt2d-preLastPt2d;  // second arm enclosing the angle
          lastVec2d.Normalize();
          vec2d=vec2d-lastVec2d;                      // vector connecting both arms
          vec2d.Normalize();

          // middle between two vectors that enclose the angle
          Vector2D pos2d = lastPt2d.GetVectorFromOrigin() + vec2d * text2dDistance * text2dDistance;

          ls->m_VtkTextActor = vtkSmartPointer<vtkTextActor>::New();

          ls->m_VtkTextActor->SetPosition(pos2d[0],pos2d[1]);
          ls->m_VtkTextActor->SetInput(buffer.str().c_str());
          ls->m_VtkTextActor->GetTextProperty()->SetColor(0.0, 1.0, 0.0);

          ls->m_VtkTextAngleActors.push_back(ls->m_VtkTextActor);
        }
      }
    }

    if(pointDataIter != itkPointSet->GetPointData()->End())
    {
      pointDataIter++;
      count++;
    }
  }

  // add each single text actor to the assembly
  for(i=0; i< ls->m_VtkTextLabelActors.size(); i++)
  {
    ls->m_PropAssembly->AddPart(ls->m_VtkTextLabelActors.at(i));
  }

  for(i=0; i< ls->m_VtkTextDistanceActors.size(); i++)
  {
    ls->m_PropAssembly->AddPart(ls->m_VtkTextDistanceActors.at(i));
  }

  for(i=0; i< ls->m_VtkTextAngleActors.size(); i++)
  {
    ls->m_PropAssembly->AddPart(ls->m_VtkTextAngleActors.at(i));
  }

  //---- CONTOUR -----//

  //create lines between the points which intersect the plane
  if (m_ShowContour)
  {
    // draw line between first and last point which is rendered
    if(m_CloseContour && NumberContourPoints > 1){
      vtkSmartPointer<vtkLine> closingLine = vtkSmartPointer<vtkLine>::New();
      closingLine->GetPointIds()->SetId(0, 0); // index of first point
      closingLine->GetPointIds()->SetId(1, NumberContourPoints-1); // index of last point
      ls->m_ContourLines->InsertNextCell(closingLine);
    }

    ls->m_VtkContourPolyData->SetPoints(ls->m_ContourPoints);
    ls->m_VtkContourPolyData->SetLines(ls->m_ContourLines);

    ls->m_VtkContourPolyDataMapper->SetInputData(ls->m_VtkContourPolyData);
    ls->m_ContourActor->SetMapper(ls->m_VtkContourPolyDataMapper);
    ls->m_ContourActor->GetProperty()->SetLineWidth(m_LineWidth);

    ls->m_PropAssembly->AddPart(ls->m_ContourActor);
  }

  // the point set must be transformed in order to obtain the appropriate glyph orientation
  // according to the current view
  vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();
  vtkSmartPointer<vtkMatrix4x4> a,b = vtkSmartPointer<vtkMatrix4x4>::New();

  a = geo2D->GetVtkTransform()->GetMatrix();
  b->DeepCopy( a );

  // delete transformation from matrix, only take orientation
  b->SetElement(3,3,1);
  b->SetElement(2,3,0);
  b->SetElement(1,3,0);
  b->SetElement(0,3,0);
  b->SetElement(3,2,0);
  b->SetElement(3,1,0);
  b->SetElement(3,0,0);

  transform->SetMatrix(  b );

  //---- UNSELECTED POINTS  -----//

  // apply properties to glyph
  ls->m_UnselectedGlyphSource2D->SetGlyphType(m_IDShapeProperty);

  if(m_FillShape)
    ls->m_UnselectedGlyphSource2D->FilledOn();
  else
    ls->m_UnselectedGlyphSource2D->FilledOff();

  // apply transform
  vtkSmartPointer<vtkTransformFilter> transformFilterU = vtkSmartPointer<vtkTransformFilter>::New();
  transformFilterU->SetInputConnection(ls->m_UnselectedGlyphSource2D->GetOutputPort());
  transformFilterU->SetTransform(transform);

  ls->m_VtkUnselectedPointListPolyData->SetPoints(ls->m_UnselectedPoints);
  ls->m_VtkUnselectedPointListPolyData->GetPointData()->SetVectors(ls->m_UnselectedScales);

  // apply transform of current plane to glyphs
  ls->m_UnselectedGlyph3D->SetSourceConnection(transformFilterU->GetOutputPort());
  ls->m_UnselectedGlyph3D->SetInputData(ls->m_VtkUnselectedPointListPolyData);
  ls->m_UnselectedGlyph3D->SetScaleModeToScaleByVector();
  ls->m_UnselectedGlyph3D->SetVectorModeToUseVector();

  ls->m_VtkUnselectedPolyDataMapper->SetInputConnection(ls->m_UnselectedGlyph3D->GetOutputPort());
  ls->m_UnselectedActor->SetMapper(ls->m_VtkUnselectedPolyDataMapper);
  ls->m_UnselectedActor->GetProperty()->SetLineWidth(m_PointLineWidth);

  ls->m_PropAssembly->AddPart(ls->m_UnselectedActor);

  //---- SELECTED POINTS  -----//

  ls->m_SelectedGlyphSource2D->SetGlyphTypeToDiamond();
  ls->m_SelectedGlyphSource2D->CrossOn();
  ls->m_SelectedGlyphSource2D->FilledOff();

  // apply transform
  vtkSmartPointer<vtkTransformFilter> transformFilterS = vtkSmartPointer<vtkTransformFilter>::New();
  transformFilterS->SetInputConnection(ls->m_SelectedGlyphSource2D->GetOutputPort());
  transformFilterS->SetTransform(transform);

  ls->m_VtkSelectedPointListPolyData->SetPoints(ls->m_SelectedPoints);
  ls->m_VtkSelectedPointListPolyData->GetPointData()->SetVectors(ls->m_SelectedScales);

  // apply transform of current plane to glyphs
  ls->m_SelectedGlyph3D->SetSourceConnection(transformFilterS->GetOutputPort());
  ls->m_SelectedGlyph3D->SetInputData(ls->m_VtkSelectedPointListPolyData);
  ls->m_SelectedGlyph3D->SetScaleModeToScaleByVector();
  ls->m_SelectedGlyph3D->SetVectorModeToUseVector();

  ls->m_VtkSelectedPolyDataMapper->SetInputConnection(ls->m_SelectedGlyph3D->GetOutputPort());
  ls->m_SelectedActor->SetMapper(ls->m_VtkSelectedPolyDataMapper);
  ls->m_SelectedActor->GetProperty()->SetLineWidth(m_PointLineWidth);

  ls->m_PropAssembly->AddPart(ls->m_SelectedActor);
}
void mitk::PointSetVtkMapper2D::GenerateDataForRenderer( mitk::BaseRenderer *renderer )
{
  const mitk::DataNode* node = GetDataNode();
  if( node == NULL )
    return;

  LocalStorage *ls = m_LSH.GetLocalStorage(renderer);

  // check whether the input data has been changed
  bool needGenerateData = ls->IsGenerateDataRequired( renderer, this, GetDataNode() );

  // toggle visibility
  bool visible = true;
  node->GetVisibility(visible, renderer, "visible");
  if(!visible)
  {
    ls->m_UnselectedActor->VisibilityOff();
    ls->m_SelectedActor->VisibilityOff();
    ls->m_ContourActor->VisibilityOff();
    ls->m_PropAssembly->VisibilityOff();
    return;
  }else{
    ls->m_PropAssembly->VisibilityOn();
  }

  node->GetBoolProperty("show contour",       m_ShowContour, renderer);
  node->GetBoolProperty("close contour",      m_CloseContour, renderer);
  node->GetBoolProperty("show points",        m_ShowPoints, renderer);
  node->GetBoolProperty("show distances",     m_ShowDistances, renderer);
  node->GetIntProperty("distance decimal digits",     m_DistancesDecimalDigits, renderer);
  node->GetBoolProperty("show angles",        m_ShowAngles, renderer);
  node->GetBoolProperty("show distant lines", m_ShowDistantLines, renderer);
  node->GetIntProperty("line width",          m_LineWidth, renderer);
  node->GetIntProperty("point line width",    m_PointLineWidth, renderer);
  node->GetIntProperty("point 2D size",       m_Point2DSize, renderer);
  node->GetBoolProperty("Pointset.2D.fill shape", m_FillShape, renderer);
  node->GetFloatProperty("Pointset.2D.distance to plane", m_DistanceToPlane, renderer );

  mitk::PointSetShapeProperty::Pointer shape = dynamic_cast<mitk::PointSetShapeProperty*>(this->GetDataNode()->GetProperty( "Pointset.2D.shape", renderer ));
  if(shape.IsNotNull())
  {
    m_IDShapeProperty = shape->GetPointSetShape();
  }

  //check for color props and use it for rendering of selected/unselected points and contour
  //due to different params in VTK (double/float) we have to convert

  float unselectedColor[4];
  double selectedColor[4]={1.0f,0.0f,0.0f,1.0f};    //red
  double contourColor[4]={1.0f,0.0f,0.0f,1.0f};     //red

  float opacity = 1.0;

  GetDataNode()->GetOpacity(opacity, renderer);

  // apply color and opacity
  if(m_ShowPoints)
  {
    ls->m_UnselectedActor->VisibilityOn();
    ls->m_SelectedActor->VisibilityOn();

    //check if there is a color property
    GetDataNode()->GetColor(unselectedColor);

    //get selected color property
    if (dynamic_cast<mitk::ColorProperty*>(this->GetDataNode()->GetPropertyList(renderer)->GetProperty("selectedcolor")) != NULL)
    {
      mitk::Color tmpColor = dynamic_cast<mitk::ColorProperty *>(this->GetDataNode()->GetPropertyList(renderer)->GetProperty("selectedcolor"))->GetValue();
      selectedColor[0] = tmpColor[0];
      selectedColor[1] = tmpColor[1];
      selectedColor[2] = tmpColor[2];
      selectedColor[3] = 1.0f; // alpha value
    }
    else if (dynamic_cast<mitk::ColorProperty*>(this->GetDataNode()->GetPropertyList(NULL)->GetProperty("selectedcolor")) != NULL)
    {
      mitk::Color tmpColor = dynamic_cast<mitk::ColorProperty *>(this->GetDataNode()->GetPropertyList(NULL)->GetProperty("selectedcolor"))->GetValue();
      selectedColor[0] = tmpColor[0];
      selectedColor[1] = tmpColor[1];
      selectedColor[2] = tmpColor[2];
      selectedColor[3] = 1.0f; // alpha value
    }

    ls->m_SelectedActor->GetProperty()->SetColor(selectedColor);
    ls->m_SelectedActor->GetProperty()->SetOpacity(opacity);

    ls->m_UnselectedActor->GetProperty()->SetColor(unselectedColor[0],unselectedColor[1],unselectedColor[2]);
    ls->m_UnselectedActor->GetProperty()->SetOpacity(opacity);
  }
  else
  {
    ls->m_UnselectedActor->VisibilityOff();
    ls-> m_SelectedActor->VisibilityOff();
  }

  if (m_ShowContour)
  {
    ls->m_ContourActor->VisibilityOn();

    //get contour color property
    if (dynamic_cast<mitk::ColorProperty*>(this->GetDataNode()->GetPropertyList(renderer)->GetProperty("contourcolor")) != NULL)
    {
      mitk::Color tmpColor = dynamic_cast<mitk::ColorProperty *>(this->GetDataNode()->GetPropertyList(renderer)->GetProperty("contourcolor"))->GetValue();
      contourColor[0] = tmpColor[0];
      contourColor[1] = tmpColor[1];
      contourColor[2] = tmpColor[2];
      contourColor[3] = 1.0f;
    }
    else if (dynamic_cast<mitk::ColorProperty*>(this->GetDataNode()->GetPropertyList(NULL)->GetProperty("contourcolor")) != NULL)
    {
      mitk::Color tmpColor = dynamic_cast<mitk::ColorProperty *>(this->GetDataNode()->GetPropertyList(NULL)->GetProperty("contourcolor"))->GetValue();
      contourColor[0] = tmpColor[0];
      contourColor[1] = tmpColor[1];
      contourColor[2] = tmpColor[2];
      contourColor[3] = 1.0f;
    }

    ls->m_ContourActor->GetProperty()->SetColor(contourColor);
    ls->m_ContourActor->GetProperty()->SetOpacity(opacity);
  }
  else
  {
    ls->m_ContourActor->VisibilityOff();
  }

  if(needGenerateData)
  {
    // create new vtk render objects (e.g. a circle for a point)
    this->CreateVTKRenderObjects(renderer);
  }
}
void mitk::ConnectomicsNetworkMapper3D::GenerateDataForRenderer(mitk::BaseRenderer* renderer)
{
  if( this->GetInput() == NULL )
  {
    return;
  }

  bool propertiesHaveChanged = this->PropertiesChanged();

  if( this->GetInput()->GetIsModified( ) || propertiesHaveChanged )
  {

  m_NetworkAssembly->Delete();
  m_NetworkAssembly = vtkPropAssembly::New();

  // Here is the part where a graph is given and converted to points and connections between points...
  std::vector< mitk::ConnectomicsNetwork::NetworkNode > vectorOfNodes = this->GetInput()->GetVectorOfAllNodes();
  std::vector< std::pair<
    std::pair< mitk::ConnectomicsNetwork::NetworkNode, mitk::ConnectomicsNetwork::NetworkNode >
    , mitk::ConnectomicsNetwork::NetworkEdge > >  vectorOfEdges = this->GetInput()->GetVectorOfAllEdges();

  // Decide on the style of rendering due to property

  if( m_ChosenRenderingScheme == connectomicsRenderingMITKScheme )
  {
    mitk::Point3D tempWorldPoint, tempCNFGeometryPoint;

    //////////////////////Prepare coloring and radius////////////

    std::vector< double > vectorOfNodeRadiusParameterValues;
    vectorOfNodeRadiusParameterValues.resize( vectorOfNodes.size() );
    double maxNodeRadiusParameterValue( FillNodeParameterVector( &vectorOfNodeRadiusParameterValues, m_NodeRadiusParameter ) );

    std::vector< double > vectorOfNodeColorParameterValues;
    vectorOfNodeColorParameterValues.resize( vectorOfNodes.size() );
    double maxNodeColorParameterValue( FillNodeParameterVector( &vectorOfNodeColorParameterValues, m_NodeColorParameter ) );

    std::vector< double > vectorOfEdgeRadiusParameterValues;
    vectorOfEdgeRadiusParameterValues.resize( vectorOfEdges.size() );
    double maxEdgeRadiusParameterValue( FillEdgeParameterVector( &vectorOfEdgeRadiusParameterValues, m_EdgeRadiusParameter ) );

    std::vector< double > vectorOfEdgeColorParameterValues;
    vectorOfEdgeColorParameterValues.resize( vectorOfEdges.size() );
    double maxEdgeColorParameterValue( FillEdgeParameterVector( &vectorOfEdgeColorParameterValues, m_EdgeColorParameter ) );

    //////////////////////Prepare Filtering//////////////////////
    // true will be rendered
    std::vector< bool > vectorOfNodeFilterBools( vectorOfNodes.size(), true );
    if( m_ChosenNodeFilter == connectomicsRenderingNodeThresholdingFilter )
    {
      FillNodeFilterBoolVector( &vectorOfNodeFilterBools, m_NodeThresholdParameter );
    }

    std::vector< bool > vectorOfEdgeFilterBools( vectorOfEdges.size(), true );
    if( m_ChosenEdgeFilter == connectomicsRenderingEdgeThresholdFilter )
    {
      FillEdgeFilterBoolVector( &vectorOfEdgeFilterBools, m_EdgeThresholdParameter );
    }

    //////////////////////Create Spheres/////////////////////////
    for(unsigned int i = 0; i < vectorOfNodes.size(); i++)
    {
      vtkSmartPointer<vtkSphereSource> sphereSource =
        vtkSmartPointer<vtkSphereSource>::New();

      for(unsigned int dimension = 0; dimension < 3; dimension++)
      {
        tempCNFGeometryPoint.SetElement( dimension , vectorOfNodes[i].coordinates[dimension] );
      }

      GetDataNode()->GetData()->GetGeometry()->IndexToWorld( tempCNFGeometryPoint, tempWorldPoint );

      sphereSource->SetCenter( tempWorldPoint[0] , tempWorldPoint[1], tempWorldPoint[2] );

      // determine radius
      double radiusFactor = vectorOfNodeRadiusParameterValues[i] / maxNodeRadiusParameterValue;

      double radius = m_NodeRadiusStart + ( m_NodeRadiusEnd - m_NodeRadiusStart) * radiusFactor;
      sphereSource->SetRadius( radius );

      vtkSmartPointer<vtkPolyDataMapper> mapper =
        vtkSmartPointer<vtkPolyDataMapper>::New();
      mapper->SetInputConnection(sphereSource->GetOutputPort());

      vtkSmartPointer<vtkActor> actor =
        vtkSmartPointer<vtkActor>::New();
      actor->SetMapper(mapper);

      // determine color
      double colorFactor = vectorOfNodeColorParameterValues[i] / maxNodeColorParameterValue;

      double redStart = m_NodeColorStart.GetElement( 0 );
      double greenStart = m_NodeColorStart.GetElement( 1 );
      double blueStart = m_NodeColorStart.GetElement( 2 );
      double redEnd = m_NodeColorEnd.GetElement( 0 );
      double greenEnd = m_NodeColorEnd.GetElement( 1 );
      double blueEnd = m_NodeColorEnd.GetElement( 2 );

      double red = redStart + ( redEnd - redStart ) * colorFactor;
      double green = greenStart + ( greenEnd - greenStart ) * colorFactor;
      double blue = blueStart + ( blueEnd - blueStart ) * colorFactor;

      actor->GetProperty()->SetColor( red, green, blue);

      if( vectorOfNodeFilterBools[i] )
      {
        m_NetworkAssembly->AddPart(actor);
      }
    }

    //////////////////////Create Tubes/////////////////////////

    for(unsigned int i = 0; i < vectorOfEdges.size(); i++)
    {

      vtkSmartPointer<vtkLineSource> lineSource =
        vtkSmartPointer<vtkLineSource>::New();

      for(unsigned int dimension = 0; dimension < 3; dimension++)
      {
        tempCNFGeometryPoint[ dimension ] = vectorOfEdges[i].first.first.coordinates[dimension];
      }

      GetDataNode()->GetData()->GetGeometry()->IndexToWorld( tempCNFGeometryPoint, tempWorldPoint );

      lineSource->SetPoint1(tempWorldPoint[0], tempWorldPoint[1],tempWorldPoint[2]  );

      for(unsigned int dimension = 0; dimension < 3; dimension++)
      {
        tempCNFGeometryPoint[ dimension ] = vectorOfEdges[i].first.second.coordinates[dimension];
      }

      GetDataNode()->GetData()->GetGeometry()->IndexToWorld( tempCNFGeometryPoint, tempWorldPoint );

      lineSource->SetPoint2(tempWorldPoint[0], tempWorldPoint[1], tempWorldPoint[2] );

      vtkSmartPointer<vtkTubeFilter> tubes = vtkSmartPointer<vtkTubeFilter>::New();
      tubes->SetInputConnection( lineSource->GetOutputPort() );
      tubes->SetNumberOfSides( 12 );

      // determine radius
      double radiusFactor = vectorOfEdgeRadiusParameterValues[i] / maxEdgeRadiusParameterValue;

      double radius = m_EdgeRadiusStart + ( m_EdgeRadiusEnd - m_EdgeRadiusStart) * radiusFactor;
      tubes->SetRadius( radius );

      // originally we used a logarithmic scaling,
      // double radiusFactor = 1.0 + ((double) vectorOfEdges[i].second.weight) / 10.0 ;
      // tubes->SetRadius( std::log10( radiusFactor ) );

      vtkSmartPointer<vtkPolyDataMapper> mapper2 =
        vtkSmartPointer<vtkPolyDataMapper>::New();
      mapper2->SetInputConnection( tubes->GetOutputPort() );

      vtkSmartPointer<vtkActor> actor =
        vtkSmartPointer<vtkActor>::New();
      actor->SetMapper(mapper2);

      // determine color
      double colorFactor = vectorOfEdgeColorParameterValues[i] / maxEdgeColorParameterValue;

      double redStart = m_EdgeColorStart.GetElement( 0 );
      double greenStart = m_EdgeColorStart.GetElement( 1 );
      double blueStart = m_EdgeColorStart.GetElement( 2 );
      double redEnd = m_EdgeColorEnd.GetElement( 0 );
      double greenEnd = m_EdgeColorEnd.GetElement( 1 );
      double blueEnd = m_EdgeColorEnd.GetElement( 2 );

      double red = redStart + ( redEnd - redStart ) * colorFactor;
      double green = greenStart + ( greenEnd - greenStart ) * colorFactor;
      double blue = blueStart + ( blueEnd - blueStart ) * colorFactor;

      actor->GetProperty()->SetColor( red, green, blue);

      if( vectorOfEdgeFilterBools[i] )
      {
        m_NetworkAssembly->AddPart(actor);
      }
    }
  }
  else if( m_ChosenRenderingScheme == connectomicsRenderingVTKScheme )
  {
    vtkSmartPointer<vtkMutableUndirectedGraph> graph =
      vtkSmartPointer<vtkMutableUndirectedGraph>::New();

    std::vector< vtkIdType > networkToVTKvector;
    networkToVTKvector.resize(vectorOfNodes.size());

    for(unsigned int i = 0; i < vectorOfNodes.size(); i++)
    {
      networkToVTKvector[vectorOfNodes[i].id] = graph->AddVertex();
    }

    for(unsigned int i = 0; i < vectorOfEdges.size(); i++)
    {
      graph->AddEdge(networkToVTKvector[vectorOfEdges[i].first.first.id], networkToVTKvector[vectorOfEdges[i].first.second.id]);
    }

    vtkSmartPointer<vtkPoints> points =
      vtkSmartPointer<vtkPoints>::New();
    for(unsigned int i = 0; i < vectorOfNodes.size(); i++)
    {
      double x = vectorOfNodes[i].coordinates[0];
      double y = vectorOfNodes[i].coordinates[1];
      double z = vectorOfNodes[i].coordinates[2];
      points->InsertNextPoint( x, y, z);
    }

    graph->SetPoints(points);

    vtkGraphLayout* layout = vtkGraphLayout::New();
    layout->SetInputData(graph);
    vtkPassThroughLayoutStrategy* ptls = vtkPassThroughLayoutStrategy::New();
    layout->SetLayoutStrategy( ptls );

    vtkGraphToPolyData* graphToPoly = vtkGraphToPolyData::New();
    graphToPoly->SetInputConnection(layout->GetOutputPort());

    // Create the standard VTK polydata mapper and actor
    // for the connections (edges) in the tree.
    vtkPolyDataMapper* edgeMapper = vtkPolyDataMapper::New();
    edgeMapper->SetInputConnection(graphToPoly->GetOutputPort());
    vtkActor* edgeActor = vtkActor::New();
    edgeActor->SetMapper(edgeMapper);
    edgeActor->GetProperty()->SetColor(0.0, 0.5, 1.0);

    // Glyph the points of the tree polydata to create
    // VTK_VERTEX cells at each vertex in the tree.
    vtkGlyph3D* vertGlyph = vtkGlyph3D::New();
    vertGlyph->SetInputConnection(0, graphToPoly->GetOutputPort());
    vtkGlyphSource2D* glyphSource = vtkGlyphSource2D::New();
    glyphSource->SetGlyphTypeToVertex();
    vertGlyph->SetInputConnection(1, glyphSource->GetOutputPort());

    // Create a mapper for the vertices, and tell the mapper
    // to use the specified color array.
    vtkPolyDataMapper* vertMapper = vtkPolyDataMapper::New();
    vertMapper->SetInputConnection(vertGlyph->GetOutputPort());
    /*if (colorArray)
    {
    vertMapper->SetScalarModeToUsePointFieldData();
    vertMapper->SelectColorArray(colorArray);
    vertMapper->SetScalarRange(colorRange);
    }*/

    // Create an actor for the vertices.  Move the actor forward
    // in the z direction so it is drawn on top of the edge actor.
    vtkActor* vertActor = vtkActor::New();
    vertActor->SetMapper(vertMapper);
    vertActor->GetProperty()->SetPointSize(5);
    vertActor->SetPosition(0, 0, 0.001);

    m_NetworkAssembly->AddPart(edgeActor);
    m_NetworkAssembly->AddPart(vertActor);
  }

  (static_cast<mitk::ConnectomicsNetwork * > ( GetDataNode()->GetData() ) )->SetIsModified( false );
  }
}
Ejemplo n.º 13
0
void mitk::PointSetVtkMapper3D::GenerateDataForRenderer( mitk::BaseRenderer *renderer )
{
  // create new vtk render objects (e.g. sphere for a point)
  this->CreateVTKRenderObjects();

  SetVtkMapperImmediateModeRendering(m_VtkSelectedPolyDataMapper);
  SetVtkMapperImmediateModeRendering(m_VtkUnselectedPolyDataMapper);

  mitk::FloatProperty::Pointer pointSizeProp = dynamic_cast<mitk::FloatProperty *>(this->GetDataNode()->GetProperty("pointsize"));
  mitk::FloatProperty::Pointer contourSizeProp = dynamic_cast<mitk::FloatProperty *>(this->GetDataNode()->GetProperty("contoursize"));
  // only create new vtk render objects if property values were changed
  if ( pointSizeProp.IsNotNull() &&  contourSizeProp.IsNotNull() )
  {
    if (m_PointSize!=pointSizeProp->GetValue() || m_ContourRadius!= contourSizeProp->GetValue())
    {
      this->CreateVTKRenderObjects();
    }
  }

  this->ApplyAllProperties(renderer, m_ContourActor);

  bool visible = true;
  GetDataNode()->GetVisibility(visible, renderer, "visible");
  if(!visible)
  {
    m_UnselectedActor->VisibilityOff();
    m_SelectedActor->VisibilityOff();
    m_ContourActor->VisibilityOff();
    return;
  }

  bool showPoints = true;
  this->GetDataNode()->GetBoolProperty("show points", showPoints);

  if(showPoints)
  {
    m_UnselectedActor->VisibilityOn();
    m_SelectedActor->VisibilityOn();
  }
  else
  {
    m_UnselectedActor->VisibilityOff();
    m_SelectedActor->VisibilityOff();
  }

  if(dynamic_cast<mitk::FloatProperty *>(this->GetDataNode()->GetProperty("opacity")) != NULL)
  {
    mitk::FloatProperty::Pointer pointOpacity =dynamic_cast<mitk::FloatProperty *>(this->GetDataNode()->GetProperty("opacity"));
    float opacity = pointOpacity->GetValue();
    m_ContourActor->GetProperty()->SetOpacity(opacity);
    m_UnselectedActor->GetProperty()->SetOpacity(opacity);
    m_SelectedActor->GetProperty()->SetOpacity(opacity);
  }

  bool makeContour = false;
  this->GetDataNode()->GetBoolProperty("show contour", makeContour);
  if (makeContour)
  {
    m_ContourActor->VisibilityOn();
  }
  else
  {
    m_ContourActor->VisibilityOff();
  }
}
vtkSmartPointer<vtkPolyData> mitk::DoseImageVtkMapper2D::CreateOutlinePolyData(mitk::BaseRenderer* renderer )
{
  vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); //the points to draw
  vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New(); //the lines to connect the points
  vtkSmartPointer<vtkUnsignedCharArray> colors = vtkSmartPointer<vtkUnsignedCharArray>::New();
  colors->SetNumberOfComponents(3);
  colors->SetName("Colors");

  float pref;
  this->GetDataNode()->GetFloatProperty(mitk::RTConstants::REFERENCE_DOSE_PROPERTY_NAME.c_str(),pref);

  mitk::IsoDoseLevelSetProperty::Pointer propIsoSet = dynamic_cast<mitk::IsoDoseLevelSetProperty* >(GetDataNode()->GetProperty(mitk::RTConstants::DOSE_ISO_LEVELS_PROPERTY_NAME.c_str()));
  mitk::IsoDoseLevelSet::Pointer isoDoseLevelSet = propIsoSet->GetValue();

  for(mitk::IsoDoseLevelSet::ConstIterator doseIT = isoDoseLevelSet->Begin(); doseIT!=isoDoseLevelSet->End();++doseIT)
  {
    if(doseIT->GetVisibleIsoLine())
    {
      this->CreateLevelOutline(renderer, &(doseIT.Value()), pref, points, lines, colors);
    }//end of if visible dose value
  }//end of loop over all does values

  mitk::IsoDoseLevelVectorProperty::Pointer propfreeIsoVec = dynamic_cast<mitk::IsoDoseLevelVectorProperty* >(GetDataNode()->GetProperty(mitk::RTConstants::DOSE_FREE_ISO_VALUES_PROPERTY_NAME.c_str()));
  mitk::IsoDoseLevelVector::Pointer frereIsoDoseLevelVec = propfreeIsoVec->GetValue();

  for(mitk::IsoDoseLevelVector::ConstIterator freeDoseIT = frereIsoDoseLevelVec->Begin(); freeDoseIT!=frereIsoDoseLevelVec->End();++freeDoseIT)
  {
    if(freeDoseIT->Value()->GetVisibleIsoLine())
    {
      this->CreateLevelOutline(renderer, freeDoseIT->Value(), pref, points, lines, colors);
    }//end of if visible dose value
  }//end of loop over all does values

  // Create a polydata to store everything in
  vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
  // Add the points to the dataset
  polyData->SetPoints(points);
  // Add the lines to the dataset
  polyData->SetLines(lines);
  polyData->GetCellData()->SetScalars(colors);
  return polyData;
}
Ejemplo n.º 15
0
void mitk::GPUVolumeMapper3D::UpdateTransferFunctions( mitk::BaseRenderer * renderer )
{
  LocalStorage *ls = m_LSH.GetLocalStorage(renderer);

  vtkPiecewiseFunction *opacityTransferFunction = m_DefaultOpacityTransferFunction;
  vtkPiecewiseFunction *gradientTransferFunction = m_DefaultGradientTransferFunction;
  vtkColorTransferFunction *colorTransferFunction = m_DefaultColorTransferFunction;

  bool isBinary = false;

  GetDataNode()->GetBoolProperty("binary", isBinary, renderer);

  if(isBinary)
  {
    opacityTransferFunction = m_BinaryOpacityTransferFunction;
    gradientTransferFunction = m_BinaryGradientTransferFunction;
    colorTransferFunction = m_BinaryColorTransferFunction;

    colorTransferFunction->RemoveAllPoints();
    float rgb[3];
    if( !GetDataNode()->GetColor( rgb,renderer ) )
       rgb[0]=rgb[1]=rgb[2]=1;
    colorTransferFunction->AddRGBPoint( 0,rgb[0],rgb[1],rgb[2] );
    colorTransferFunction->Modified();
  }
  else
  {
    mitk::TransferFunctionProperty *transferFunctionProp =
      dynamic_cast<mitk::TransferFunctionProperty*>(this->GetDataNode()->GetProperty("TransferFunction",renderer));

    if( transferFunctionProp )
    {
      opacityTransferFunction = transferFunctionProp->GetValue()->GetScalarOpacityFunction();
      gradientTransferFunction = transferFunctionProp->GetValue()->GetGradientOpacityFunction();
      colorTransferFunction = transferFunctionProp->GetValue()->GetColorTransferFunction();
    }
  }

  if(ls->m_gpuInitialized)
  {
    ls->m_VolumePropertyGPU->SetColor( colorTransferFunction );
    ls->m_VolumePropertyGPU->SetScalarOpacity( opacityTransferFunction );
    ls->m_VolumePropertyGPU->SetGradientOpacity( gradientTransferFunction );
  }

// Only with VTK 5.6 or above
#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) ))

  if(ls->m_rayInitialized)
  {
    ls->m_VolumePropertyRAY->SetColor( colorTransferFunction );
    ls->m_VolumePropertyRAY->SetScalarOpacity( opacityTransferFunction );
    ls->m_VolumePropertyRAY->SetGradientOpacity( gradientTransferFunction );
  }

#endif

  if(ls->m_cpuInitialized)
  {
    ls->m_VolumePropertyCPU->SetColor( colorTransferFunction );
    ls->m_VolumePropertyCPU->SetScalarOpacity( opacityTransferFunction );
    ls->m_VolumePropertyCPU->SetGradientOpacity( gradientTransferFunction );
  }
}
Ejemplo n.º 16
0
bool mitk::PlanarFigureInteractor::CheckFigureFinished( const InteractionEvent* /*interactionEvent*/ )
{
  mitk::PlanarFigure *planarFigure = dynamic_cast<mitk::PlanarFigure *>( GetDataNode()->GetData() );
  return ( planarFigure->GetNumberOfControlPoints() >= planarFigure->GetMaximumNumberOfControlPoints() );
}
Ejemplo n.º 17
0
bool mitk::GPUVolumeMapper3D::IsMIPEnabled( mitk::BaseRenderer * renderer )
{
  bool value = false;
  return GetDataNode()->GetBoolProperty("volumerendering.usemip",value,renderer) && value;
}
Ejemplo n.º 18
0
bool mitk::PlanarFigureInteractor::AddPoint(StateMachineAction*, InteractionEvent* interactionEvent)
{
  mitk::InteractionPositionEvent* positionEvent = dynamic_cast<mitk::InteractionPositionEvent*>( interactionEvent );
  if ( positionEvent == NULL )
    return false;

  bool selected = false;
  bool isEditable = true;
  GetDataNode()->GetBoolProperty("selected", selected);
  GetDataNode()->GetBoolProperty( "planarfigure.iseditable", isEditable );

  if ( !selected || !isEditable )
  {
    return false;
  }

  mitk::PlanarFigure *planarFigure = dynamic_cast<mitk::PlanarFigure *>(
    GetDataNode()->GetData() );

  mitk::PlaneGeometry *planarFigureGeometry =
    dynamic_cast< PlaneGeometry * >( planarFigure->GetGeometry( 0 ) );
  mitk::AbstractTransformGeometry *abstractTransformGeometry =
    dynamic_cast< AbstractTransformGeometry * >( planarFigure->GetGeometry( 0 ) );

  if ( abstractTransformGeometry != NULL)
    return false;

  // If the planarFigure already has reached the maximum number
  if ( planarFigure->GetNumberOfControlPoints() >= planarFigure->GetMaximumNumberOfControlPoints() )
  {
    return false;
  }

  // Extract point in 2D world coordinates (relative to PlaneGeometry of
  // PlanarFigure)
  Point2D point2D, projectedPoint;
  if ( !this->TransformPositionEventToPoint2D( positionEvent, planarFigureGeometry, point2D ) )
  {
    return false;
  }

  // TODO: check segment of polyline we clicked in
  int nextIndex = -1;

  // We only need to check which position to insert the control point
  // when interacting with a PlanarPolygon. For all other types
  // new control points will always be appended

  /*
  * Added check for "initiallyplaced" due to bug 13097:
  *
  * There are two possible cases in which a point can be inserted into a PlanarPolygon:
  *
  * 1. The figure is currently drawn -> the point will be appended at the end of the figure
  * 2. A point is inserted at a userdefined position after the initial placement of the figure is finished
  *
  * In the second case we need to determine the proper insertion index. In the first case the index always has
  * to be -1 so that the point is appended to the end.
  *
  * These changes are necessary because of a mac os x specific issue: If a users draws a PlanarPolygon then the
  * next point to be added moves according to the mouse position. If then the user left clicks in order to add
  * a point one would assume the last move position is identical to the left click position. This is actually the
  * case for windows and linux but somehow NOT for mac. Because of the insertion logic of a new point in the
  * PlanarFigure then for mac the wrong current selected point is determined.
  *
  * With this check here this problem can be avoided. However a redesign of the insertion logic should be considered
  */
  bool isFigureFinished = false;
  planarFigure->GetPropertyList()->GetBoolProperty( "initiallyplaced", isFigureFinished );

  mitk::BaseRenderer *renderer = interactionEvent->GetSender();
  const PlaneGeometry *projectionPlane = renderer->GetCurrentWorldPlaneGeometry();

  if ( dynamic_cast<mitk::PlanarPolygon*>( planarFigure ) && isFigureFinished)
  {
    nextIndex = this->IsPositionOverFigure(
      positionEvent,
      planarFigure,
      planarFigureGeometry,
      projectionPlane,
      renderer->GetDisplayGeometry(),
      projectedPoint
      );
  }


  // Add point as new control point
  renderer->GetDisplayGeometry()->DisplayToWorld( projectedPoint, projectedPoint );

  if ( planarFigure->IsPreviewControlPointVisible() )
  {
    point2D = planarFigure->GetPreviewControlPoint();
  }

  planarFigure->AddControlPoint( point2D, nextIndex );

  if ( planarFigure->IsPreviewControlPointVisible() )
  {
    planarFigure->SelectControlPoint( nextIndex );
    planarFigure->ResetPreviewContolPoint();
  }

  // Re-evaluate features
  planarFigure->EvaluateFeatures();
  //this->LogPrintPlanarFigureQuantities( planarFigure );

  // Update rendered scene
  renderer->GetRenderingManager()->RequestUpdateAll();

  return true;
}
void mitk::UnstructuredGridVtkMapper3D::GenerateDataForRenderer(mitk::BaseRenderer* renderer)
{

  mitk::DataNode::ConstPointer node = this->GetDataNode();

  BaseLocalStorage *ls = m_LSH.GetLocalStorage(renderer);
  bool needGenerateData = ls->IsGenerateDataRequired( renderer, this, GetDataNode() );

  if(needGenerateData)
  {
    ls->UpdateGenerateDataTime();

    m_Assembly->VisibilityOn();

    m_ActorWireframe->GetProperty()->SetAmbient(1.0);
    m_ActorWireframe->GetProperty()->SetDiffuse(0.0);
    m_ActorWireframe->GetProperty()->SetSpecular(0.0);

    mitk::TransferFunctionProperty::Pointer transferFuncProp;
    if (node->GetProperty(transferFuncProp, "TransferFunction"))
    {
      mitk::TransferFunction::Pointer transferFunction = transferFuncProp->GetValue();
      if (transferFunction->GetColorTransferFunction()->GetSize() < 2)
      {
        mitk::UnstructuredGrid::Pointer input  = const_cast< mitk::UnstructuredGrid* >(this->GetInput());
        if (input.IsNull()) return;

        vtkUnstructuredGrid * grid = input->GetVtkUnstructuredGrid(this->GetTimestep());
        if (grid == 0) return;

        double* scalarRange = grid->GetScalarRange();
        vtkColorTransferFunction* colorFunc = transferFunction->GetColorTransferFunction();
        colorFunc->RemoveAllPoints();
        colorFunc->AddRGBPoint(scalarRange[0], 1, 0, 0);
        colorFunc->AddRGBPoint((scalarRange[0] + scalarRange[1])/2.0, 0, 1, 0);
        colorFunc->AddRGBPoint(scalarRange[1], 0, 0, 1);
      }
    }
  }

  bool visible = true;
  GetDataNode()->GetVisibility(visible, renderer, "visible");

  if(!visible)
  {
    m_Assembly->VisibilityOff();
    return;
  }

  //
  // get the TimeGeometry of the input object
  //
  mitk::UnstructuredGrid::Pointer input  = const_cast< mitk::UnstructuredGrid* >( this->GetInput() );

  //
  // set the input-object at time t for the mapper
  //
  vtkUnstructuredGrid * grid = input->GetVtkUnstructuredGrid( this->GetTimestep() );
  if(grid == 0)
  {
    m_Assembly->VisibilityOff();
    return;
  }

  m_Assembly->VisibilityOn();

  m_VtkTriangleFilter->SetInputData(grid);
  m_VtkDataSetMapper->SetInput(grid);
  m_VtkDataSetMapper2->SetInput(grid);

  bool clip = false;
  node->GetBoolProperty("enable clipping", clip);
  mitk::DataNode::Pointer bbNode = renderer->GetDataStorage()->GetNamedDerivedNode("Clipping Bounding Object", node);
  if (clip && bbNode.IsNotNull())
  {
    m_VtkDataSetMapper->SetBoundingObject(dynamic_cast<mitk::BoundingObject*>(bbNode->GetData()));
    m_VtkDataSetMapper2->SetBoundingObject(dynamic_cast<mitk::BoundingObject*>(bbNode->GetData()));
  }
  else
  {
    m_VtkDataSetMapper->SetBoundingObject(0);
    m_VtkDataSetMapper2->SetBoundingObject(0);
  }

  //
  // apply properties read from the PropertyList
  //
  ApplyProperties(0, renderer);
}
Ejemplo n.º 20
0
bool mitk::PlanarFigureInteractor::HideControlPoints( StateMachineAction*, InteractionEvent* /*interactionEvent*/ )
{
  GetDataNode()->SetBoolProperty( "planarfigure.drawcontrolpoints", false );
  return true;
}
Ejemplo n.º 21
0
void mitk::VolumeDataVtkMapper3D::GenerateDataForRenderer( mitk::BaseRenderer *renderer )
{
  SetVtkMapperImmediateModeRendering(m_BoundingBoxMapper);

  mitk::Image *input = const_cast< mitk::Image * >( this->GetInput() );
  if ( !input || !input->IsInitialized() )
    return;

  vtkRenderWindow* renderWindow = renderer->GetRenderWindow();

  bool volumeRenderingEnabled = true;

  bool visible = true;

  GetDataNode()->GetVisibility(visible, renderer, "visible");

  if ( !visible ||
      this->GetDataNode() == NULL ||
      dynamic_cast<mitk::BoolProperty*>(GetDataNode()->GetProperty("volumerendering",renderer))==NULL ||
      dynamic_cast<mitk::BoolProperty*>(GetDataNode()->GetProperty("volumerendering",renderer))->GetValue() == false
    )
  {
    volumeRenderingEnabled = false;

    // Check if a bounding box should be displayed around the dataset
    // (even if volume rendering is disabled)
    bool hasBoundingBox = false;
    this->GetDataNode()->GetBoolProperty( "bounding box", hasBoundingBox );

    if ( !hasBoundingBox )
    {
      m_BoundingBoxActor->VisibilityOff();
    }
    else
    {
      m_BoundingBoxActor->VisibilityOn();

      const BoundingBox::BoundsArrayType &bounds =
        input->GetTimeSlicedGeometry()->GetBounds();

      m_BoundingBox->SetBounds(
        bounds[0], bounds[1],
        bounds[2], bounds[3],
        bounds[4], bounds[5] );

      ColorProperty *colorProperty;
      if ( this->GetDataNode()->GetProperty(
        colorProperty, "color" ) )
      {
        const mitk::Color &color = colorProperty->GetColor();
        m_BoundingBoxActor->GetProperty()->SetColor(
          color[0], color[1], color[2] );
      }
      else
      {
        m_BoundingBoxActor->GetProperty()->SetColor(
          1.0, 1.0, 1.0 );
      }
    }
  }

  // Don't do anything if VR is disabled
  if ( !volumeRenderingEnabled )
  {
    m_VolumeLOD->VisibilityOff();
    return;
  }
  else
  {
        mitk::VtkVolumeRenderingProperty* vrp=dynamic_cast<mitk::VtkVolumeRenderingProperty*>(GetDataNode()->GetProperty("volumerendering configuration",renderer));
        if(vrp)
        {
          int renderingValue = vrp->GetValueAsId();

          switch(renderingValue)
          {
              case  VTK_VOLUME_RAY_CAST_MIP_FUNCTION:
              {
                  vtkVolumeRayCastMIPFunction* mipFunction = vtkVolumeRayCastMIPFunction::New();
                  m_HiResMapper->SetVolumeRayCastFunction(mipFunction);
                  mipFunction->Delete();
                  MITK_INFO <<"in switch" <<std::endl;
                  break;
              }

              case VTK_RAY_CAST_COMPOSITE_FUNCTION:
              {
                  vtkVolumeRayCastCompositeFunction* compositeFunction = vtkVolumeRayCastCompositeFunction::New();
                  compositeFunction->SetCompositeMethodToClassifyFirst();
                  m_HiResMapper->SetVolumeRayCastFunction(compositeFunction);
                  compositeFunction->Delete();
                  break;
              }
              default:
                  MITK_ERROR <<"Warning: invalid volume rendering option.  " << std::endl;

          }
        }
    m_VolumeLOD->VisibilityOn();
  }

  this->SetPreferences();
/*
  switch ( mitk::RenderingManager::GetInstance()->GetNextLOD( renderer ) )
  {
  case 0:
    m_VolumeLOD->SetSelectedLODID(m_MedResID);  m_LowResID );
    break;

  default:
  case 1:
    m_VolumeLOD->SetSelectedLODID( m_HiResID );
    break;
  }
*/
  m_VolumeLOD->SetSelectedLODID( m_HiResID );

  assert(input->GetTimeSlicedGeometry());

  const Geometry3D* worldgeometry = renderer->GetCurrentWorldGeometry();
  if(worldgeometry==NULL)
  {
    GetDataNode()->SetProperty("volumerendering",mitk::BoolProperty::New(false));
    return;
  }

  vtkImageData *inputData = input->GetVtkImageData( this->GetTimestep() );
  if(inputData==NULL)
    return;


  m_ImageCast->SetInput( inputData );

  //If mask exists, process mask before resampling.
  if (this->m_Mask)
  {
    this->m_ImageMaskFilter->SetImageInput(this->m_UnitSpacingImageFilter->GetOutput());
    this->m_Resampler->SetInput(this->m_ImageMaskFilter->GetOutput());
    this->m_HiResMapper->SetInput(this->m_ImageMaskFilter->GetOutput());
  }
  else
  {
    this->m_Resampler->SetInput(this->m_UnitSpacingImageFilter->GetOutput());
    this->m_HiResMapper->SetInput(this->m_UnitSpacingImageFilter->GetOutput());
  }

  this->UpdateTransferFunctions( renderer );

  vtkRenderWindowInteractor *interactor = renderWindow->GetInteractor();

  float frameRate;
  if( this->GetDataNode()->GetFloatProperty( "framerate", frameRate ) && frameRate > 0 && frameRate <= 60)
  {
    interactor->SetDesiredUpdateRate(  frameRate );
    interactor->SetStillUpdateRate( frameRate );
  }
  else if( frameRate > 60 )
  {
    this->GetDataNode()->SetProperty( "framerate",mitk::FloatProperty::New(60));
    interactor->SetDesiredUpdateRate(  60 );
    interactor->SetStillUpdateRate( 60 );
  }
  else
  {
    this->GetDataNode()->SetProperty( "framerate",mitk::FloatProperty::New(0.00001));
    interactor->SetDesiredUpdateRate(  0.00001 );
    interactor->SetStillUpdateRate( 0.00001 );
  }

  if ( m_RenderWindowInitialized.find( renderWindow ) == m_RenderWindowInitialized.end() )
  {
    m_RenderWindowInitialized.insert( renderWindow );

//    mitk::RenderingManager::GetInstance()->SetNextLOD( 0, renderer );

    mitk::RenderingManager::GetInstance()->SetShading( true, 0 );
    mitk::RenderingManager::GetInstance()->SetShading( true, 1 );
    //mitk::RenderingManager::GetInstance()->SetShading( true, 2 );

    mitk::RenderingManager::GetInstance()->SetShadingValues(
      m_VolumePropertyHigh->GetAmbient(),
      m_VolumePropertyHigh->GetDiffuse(),
      m_VolumePropertyHigh->GetSpecular(),
      m_VolumePropertyHigh->GetSpecularPower());

    mitk::RenderingManager::GetInstance()->SetClippingPlaneStatus(false);
  }

  this->SetClippingPlane( interactor );
}
Ejemplo n.º 22
0
bool mitk::PlanarFigureInteractor::SelectFigure( StateMachineAction*, InteractionEvent* /*interactionEvent*/ )
{
  mitk::PlanarFigure *planarFigure = dynamic_cast<mitk::PlanarFigure *>( GetDataNode()->GetData() );
  planarFigure->InvokeEvent( SelectPlanarFigureEvent() );
  return false;
}
Ejemplo n.º 23
0
const mitk::Image* mitk::VolumeDataVtkMapper3D::GetInput()
{
  return static_cast<const mitk::Image*> ( GetDataNode()->GetData() );
}
Ejemplo n.º 24
0
void mitk::PolyDataGLMapper2D::Paint( mitk::BaseRenderer * renderer )
{
    if ( IsVisible( renderer ) == false )
        return ;

    // ok, das ist aus GenerateData kopiert
    mitk::BaseData::Pointer input = const_cast<mitk::BaseData*>( GetData() );

    assert( input );

    input->Update();

    vtkPolyData * vtkpolydata = this->GetVtkPolyData();
    assert( vtkpolydata );


    vtkLinearTransform * vtktransform = GetDataNode() ->GetVtkTransform();

    if (vtktransform)
    {
      vtkLinearTransform * inversetransform = vtktransform->GetLinearInverse();

      Geometry2D::ConstPointer worldGeometry = renderer->GetCurrentWorldGeometry2D();
      PlaneGeometry::ConstPointer worldPlaneGeometry = dynamic_cast<const PlaneGeometry*>( worldGeometry.GetPointer() );

      if ( vtkpolydata != NULL )
      {
          Point3D point;
          Vector3D normal;

          if(worldPlaneGeometry.IsNotNull())
          {
            // set up vtkPlane according to worldGeometry
            point=worldPlaneGeometry->GetOrigin();
            normal=worldPlaneGeometry->GetNormal(); normal.Normalize();
            m_Plane->SetTransform((vtkAbstractTransform*)NULL);
          }
          else
          {
            //@FIXME: does not work correctly. Does m_Plane->SetTransform really transforms a "plane plane" into a "curved plane"?
            return;
            AbstractTransformGeometry::ConstPointer worldAbstractGeometry = dynamic_cast<const AbstractTransformGeometry*>(renderer->GetCurrentWorldGeometry2D());
            if(worldAbstractGeometry.IsNotNull())
            {
              // set up vtkPlane according to worldGeometry
              point=const_cast<mitk::BoundingBox*>(worldAbstractGeometry->GetParametricBoundingBox())->GetMinimum();
              FillVector3D(normal, 0, 0, 1);
              m_Plane->SetTransform(worldAbstractGeometry->GetVtkAbstractTransform()->GetInverse());
            }
            else
              return;
          }

          vtkFloatingPointType vp[ 3 ], vnormal[ 3 ];

          vnl2vtk(point.Get_vnl_vector(), vp);
          vnl2vtk(normal.Get_vnl_vector(), vnormal);

          //normally, we would need to transform the surface and cut the transformed surface with the cutter.
          //This might be quite slow. Thus, the idea is, to perform an inverse transform of the plane instead.
          //@todo It probably does not work for scaling operations yet:scaling operations have to be
          //dealed with after the cut is performed by scaling the contour.
          inversetransform->TransformPoint( vp, vp );
          inversetransform->TransformNormalAtPoint( vp, vnormal, vnormal );

          m_Plane->SetOrigin( vp );
          m_Plane->SetNormal( vnormal );

          // set data into cutter
          m_Cutter->SetInput( vtkpolydata );
          //    m_Cutter->GenerateCutScalarsOff();
          //    m_Cutter->SetSortByToSortByCell();

          // calculate the cut
          m_Cutter->Update();

          // fetch geometry
          mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry();
          assert( displayGeometry );
          //  float toGL=displayGeometry->GetSizeInDisplayUnits()[1];

          //apply color and opacity read from the PropertyList
          ApplyProperties( renderer );

          // traverse the cut contour
          vtkPolyData * contour = m_Cutter->GetOutput();

          vtkPoints *vpoints = contour->GetPoints();
          vtkCellArray *vpolys = contour->GetLines();
          vtkPointData *vpointdata = contour->GetPointData();
          vtkDataArray* vscalars = vpointdata->GetScalars();

          vtkCellData *vcelldata = contour->GetCellData();
          vtkDataArray* vcellscalars = vcelldata->GetScalars();

          int i, numberOfCells = vpolys->GetNumberOfCells();

          Point3D p;
          Point2D p2d, last, first;

          vpolys->InitTraversal();
          vtkScalarsToColors* lut = GetVtkLUT();
          assert ( lut != NULL );

          for ( i = 0;i < numberOfCells;++i )
          {
              vtkIdType *cell(NULL);
              vtkIdType cellSize(0);

              vpolys->GetNextCell( cellSize, cell );

              if ( m_ColorByCellData )
              {  // color each cell according to cell data
                vtkFloatingPointType* color = lut->GetColor( vcellscalars->GetComponent( i, 0 ) );
                glColor3f( color[ 0 ], color[ 1 ], color[ 2 ] );
              }
              if ( m_ColorByPointData )
              {
                vtkFloatingPointType* color = lut->GetColor( vscalars->GetComponent( cell[0], 0 ) );
                glColor3f( color[ 0 ], color[ 1 ], color[ 2 ] );
              }

              glBegin ( GL_LINE_LOOP );
              for ( int j = 0;j < cellSize;++j )
              {
                  vpoints->GetPoint( cell[ j ], vp );
                  //take transformation via vtktransform into account
                  vtktransform->TransformPoint( vp, vp );

                  vtk2itk( vp, p );

                  //convert 3D point (in mm) to 2D point on slice (also in mm)
                  worldGeometry->Map( p, p2d );

                  //convert point (until now mm and in worldcoordinates) to display coordinates (units )
                  displayGeometry->WorldToDisplay( p2d, p2d );

                  //convert display coordinates ( (0,0) is top-left ) in GL coordinates ( (0,0) is bottom-left )
                  //p2d[1]=toGL-p2d[1];

                  //add the current vertex to the line
                  glVertex2f( p2d[0], p2d[1] );
              }
              glEnd ();
          }
      }
    }
}
Ejemplo n.º 25
0
const mitk::PointSet *mitk::PointSetVtkMapper3D::GetInput()
{
  return static_cast<const mitk::PointSet *>(GetDataNode()->GetData());
}
const mitk::ConnectomicsNetwork *mitk::ConnectomicsNetworkMapper3D::GetInput()
{
  return static_cast<const mitk::ConnectomicsNetwork *>(GetDataNode()->GetData());
}
Ejemplo n.º 27
0
bool mitk::PointSetDataInteractor::FinishMove(StateMachineAction* stateMachineAction, InteractionEvent* interactionEvent)
{
  IsClosedContour(stateMachineAction, interactionEvent);
  GetDataNode()->SetProperty("contourcolor", ColorProperty::New(1.0, 0.0, 0.0));
  return true;
}
void mitk::ConnectomicsNetworkMapper3D::GenerateDataForRenderer(mitk::BaseRenderer *renderer)
{
  if (this->GetInput() == nullptr)
  {
    m_TextOverlay3D->UnRegisterMicroservice();
    return;
  }

  bool propertiesHaveChanged = this->PropertiesChanged();

  if (this->GetInput()->GetIsModified() || propertiesHaveChanged)
  {
    m_NetworkAssembly->Delete();
    m_NetworkAssembly = vtkPropAssembly::New();

    // Here is the part where a graph is given and converted to points and connections between points...
    std::vector<mitk::ConnectomicsNetwork::NetworkNode> vectorOfNodes = this->GetInput()->GetVectorOfAllNodes();
    std::vector<std::pair<std::pair<mitk::ConnectomicsNetwork::NetworkNode, mitk::ConnectomicsNetwork::NetworkNode>,
                          mitk::ConnectomicsNetwork::NetworkEdge>>
      vectorOfEdges = this->GetInput()->GetVectorOfAllEdges();

    // Decide on the style of rendering due to property
    if (m_ChosenRenderingScheme == connectomicsRenderingMITKScheme)
    {
      mitk::Point3D tempWorldPoint, tempCNFGeometryPoint;

      ////// Prepare BalloonWidgets/Overlays: ////////////////////
      if ((m_ChosenNodeLabel == "" || m_ChosenNodeLabel == "-1") && m_TextOverlay3D)
      {
        m_TextOverlay3D->UnRegisterMicroservice();
        GetDataNode()->SetProperty(
          connectomicsRenderingBalloonTextName.c_str(), mitk::StringProperty::New(""), nullptr);
        GetDataNode()->SetProperty(
          connectomicsRenderingBalloonNodeStatsName.c_str(), mitk::StringProperty::New(""), nullptr);
      }

      //////////////////////Prepare coloring and radius////////////
      std::vector<double> vectorOfNodeRadiusParameterValues;
      vectorOfNodeRadiusParameterValues.resize(vectorOfNodes.size());
      double maxNodeRadiusParameterValue(
        FillNodeParameterVector(&vectorOfNodeRadiusParameterValues, m_NodeRadiusParameter));

      std::vector<double> vectorOfNodeColorParameterValues;
      vectorOfNodeColorParameterValues.resize(vectorOfNodes.size());
      double maxNodeColorParameterValue(
        FillNodeParameterVector(&vectorOfNodeColorParameterValues, m_NodeColorParameter));

      std::vector<double> vectorOfEdgeRadiusParameterValues;
      vectorOfEdgeRadiusParameterValues.resize(vectorOfEdges.size());
      double maxEdgeRadiusParameterValue(
        FillEdgeParameterVector(&vectorOfEdgeRadiusParameterValues, m_EdgeRadiusParameter));

      std::vector<double> vectorOfEdgeColorParameterValues;
      vectorOfEdgeColorParameterValues.resize(vectorOfEdges.size());
      double maxEdgeColorParameterValue(
        FillEdgeParameterVector(&vectorOfEdgeColorParameterValues, m_EdgeColorParameter));

      //////////////////////Prepare Filtering//////////////////////
      // true will be rendered
      std::vector<bool> vectorOfNodeFilterBools(vectorOfNodes.size(), true);
      if (m_ChosenNodeFilter == connectomicsRenderingNodeThresholdingFilter)
      {
        FillNodeFilterBoolVector(&vectorOfNodeFilterBools, m_NodeThresholdParameter);
      }

      std::vector<bool> vectorOfEdgeFilterBools(vectorOfEdges.size(), true);
      if (m_ChosenEdgeFilter == connectomicsRenderingEdgeThresholdFilter)
      {
        FillEdgeFilterBoolVector(&vectorOfEdgeFilterBools, m_EdgeThresholdParameter);
      }

      //////////////////////Create Spheres/////////////////////////
      std::stringstream
        nodeLabelStream; // local stream variable to hold csv list of node label names and node label numbers.

      for (unsigned int i = 0; i < vectorOfNodes.size(); i++)
      {
        vtkSmartPointer<vtkSphereSource> sphereSource = vtkSmartPointer<vtkSphereSource>::New();

        for (unsigned int dimension = 0; dimension < 3; dimension++)
        {
          tempCNFGeometryPoint.SetElement(dimension, vectorOfNodes[i].coordinates[dimension]);
        }

        GetDataNode()->GetData()->GetGeometry()->IndexToWorld(tempCNFGeometryPoint, tempWorldPoint);

        sphereSource->SetCenter(tempWorldPoint[0], tempWorldPoint[1], tempWorldPoint[2]);

        // determine radius
        double radiusFactor = vectorOfNodeRadiusParameterValues[i] / maxNodeRadiusParameterValue;

        double radius = m_NodeRadiusStart + (m_NodeRadiusEnd - m_NodeRadiusStart) * radiusFactor;
        sphereSource->SetRadius(radius);

        vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
        mapper->SetInputConnection(sphereSource->GetOutputPort());

        vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
        actor->SetMapper(mapper);

        // determine color
        double colorFactor = vectorOfNodeColorParameterValues[i] / maxNodeColorParameterValue;

        double redStart = m_NodeColorStart.GetElement(0);
        double greenStart = m_NodeColorStart.GetElement(1);
        double blueStart = m_NodeColorStart.GetElement(2);
        double redEnd = m_NodeColorEnd.GetElement(0);
        double greenEnd = m_NodeColorEnd.GetElement(1);
        double blueEnd = m_NodeColorEnd.GetElement(2);

        double red = redStart + (redEnd - redStart) * colorFactor;
        double green = greenStart + (greenEnd - greenStart) * colorFactor;
        double blue = blueStart + (blueEnd - blueStart) * colorFactor;

        actor->GetProperty()->SetColor(red, green, blue);

        // append to csv list of nodelabels.
        nodeLabelStream << m_Translator->GetName(std::stoi(vectorOfNodes[i].label)) << ": " << vectorOfNodes[i].label
                        << ",";

        if (vectorOfNodeFilterBools[i])
        {
          if (vectorOfNodes[i].label == m_ChosenNodeLabel)
          { // if chosen and enabled, show information in Balloon or TextOverlay:
            // What to show:
            std::stringstream balloonStringstream;
            balloonStringstream << "Node id: " << vectorOfNodes[i].id << "\nlabel: " << vectorOfNodes[i].label
                                << "\nname: " << m_Translator->GetName(std::stoi(vectorOfNodes[i].label)) << std::endl;
            m_BalloonText = balloonStringstream.str();
            GetDataNode()->SetProperty(
              connectomicsRenderingBalloonTextName.c_str(), mitk::StringProperty::New(m_BalloonText.c_str()), nullptr);

            std::stringstream balloonNodeStatsStream;
            balloonNodeStatsStream << "Coordinates: (" << vectorOfNodes[i].coordinates[0] << " ; "
                                   << vectorOfNodes[i].coordinates[1] << " ; " << vectorOfNodes[i].coordinates[2]
                                   << " )"
                                   << "\nDegree: " << (this->GetInput()->GetDegreeOfNodes()).at(vectorOfNodes[i].id)
                                   << "\nBetweenness centrality: "
                                   << (this->GetInput()->GetNodeBetweennessVector()).at(vectorOfNodes[i].id)
                                   << "\nClustering coefficient: "
                                   << (this->GetInput()->GetLocalClusteringCoefficients()).at(vectorOfNodes[i].id)
                                   << std::endl;
            m_BalloonNodeStats = balloonNodeStatsStream.str();
            GetDataNode()->SetProperty(connectomicsRenderingBalloonNodeStatsName.c_str(),
                                       mitk::StringProperty::New(m_BalloonNodeStats.c_str()),
                                       nullptr);

            // Where to show:
            float r[3];
            r[0] = vectorOfNodes[i].coordinates[0];
            r[1] = vectorOfNodes[i].coordinates[1];
            r[2] = vectorOfNodes[i].coordinates[2];
            mitk::Point3D BalloonAnchor(r);
            mitk::Point3D BalloonAnchorWorldCoord(r);
            GetDataNode()->GetData()->GetGeometry()->IndexToWorld(BalloonAnchor, BalloonAnchorWorldCoord);

            // How to show:
            if (m_ChosenNodeLabel != "-1")
            {
              if (m_TextOverlay3D != nullptr)
              {
                m_TextOverlay3D->UnRegisterMicroservice();
              }
              m_TextOverlay3D = mitk::TextAnnotation3D::New();

              mitk::ManualPlacementAnnotationRenderer::AddAnnotation(m_TextOverlay3D.GetPointer(), renderer);
              m_TextOverlay3D->SetFontSize(2);
              m_TextOverlay3D->SetColor(0.96, 0.69, 0.01);
              m_TextOverlay3D->SetOpacity(0.81);
              m_TextOverlay3D->SetPosition3D(BalloonAnchorWorldCoord);
              m_TextOverlay3D->SetText("...." + m_BalloonText);
              m_TextOverlay3D->SetForceInForeground(true); // TODO: does not work anymore.
              m_TextOverlay3D->SetVisibility(GetDataNode()->IsVisible(renderer));
              // Colorize chosen node:
              actor->GetProperty()->SetColor(1.0, 0.69, 0.01);
            }
          }
          m_NetworkAssembly->AddPart(actor);
        }
      }
      m_AllNodeLabels = nodeLabelStream.str();              // Store all Node Names and Node Labels in 1 Property.
      m_AllNodeLabels.erase(m_AllNodeLabels.rfind(","), 1); // remove trailing ,.
      GetDataNode()->SetProperty(connectomicsRenderingBalloonAllNodeLabelsName.c_str(),
                                 mitk::StringProperty::New(m_AllNodeLabels.c_str()),
                                 nullptr);

      //////////////////////Create Tubes/////////////////////////
      for (unsigned int i = 0; i < vectorOfEdges.size(); i++)
      {
        vtkSmartPointer<vtkLineSource> lineSource = vtkSmartPointer<vtkLineSource>::New();

        for (unsigned int dimension = 0; dimension < 3; dimension++)
        {
          tempCNFGeometryPoint[dimension] = vectorOfEdges[i].first.first.coordinates[dimension];
        }

        GetDataNode()->GetData()->GetGeometry()->IndexToWorld(tempCNFGeometryPoint, tempWorldPoint);

        lineSource->SetPoint1(tempWorldPoint[0], tempWorldPoint[1], tempWorldPoint[2]);

        for (unsigned int dimension = 0; dimension < 3; dimension++)
        {
          tempCNFGeometryPoint[dimension] = vectorOfEdges[i].first.second.coordinates[dimension];
        }

        GetDataNode()->GetData()->GetGeometry()->IndexToWorld(tempCNFGeometryPoint, tempWorldPoint);

        lineSource->SetPoint2(tempWorldPoint[0], tempWorldPoint[1], tempWorldPoint[2]);

        vtkSmartPointer<vtkTubeFilter> tubes = vtkSmartPointer<vtkTubeFilter>::New();
        tubes->SetInputConnection(lineSource->GetOutputPort());
        tubes->SetNumberOfSides(12);

        // determine radius
        double radiusFactor = vectorOfEdgeRadiusParameterValues[i] / maxEdgeRadiusParameterValue;

        double radius = m_EdgeRadiusStart + (m_EdgeRadiusEnd - m_EdgeRadiusStart) * radiusFactor;
        tubes->SetRadius(radius);

        // originally we used a logarithmic scaling,
        // double radiusFactor = 1.0 + ((double) vectorOfEdges[i].second.weight) / 10.0 ;
        // tubes->SetRadius( std::log10( radiusFactor ) );

        vtkSmartPointer<vtkPolyDataMapper> mapper2 = vtkSmartPointer<vtkPolyDataMapper>::New();
        mapper2->SetInputConnection(tubes->GetOutputPort());

        vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
        actor->SetMapper(mapper2);

        // determine color
        double colorFactor = vectorOfEdgeColorParameterValues[i] / maxEdgeColorParameterValue;

        double redStart = m_EdgeColorStart.GetElement(0);
        double greenStart = m_EdgeColorStart.GetElement(1);
        double blueStart = m_EdgeColorStart.GetElement(2);
        double redEnd = m_EdgeColorEnd.GetElement(0);
        double greenEnd = m_EdgeColorEnd.GetElement(1);
        double blueEnd = m_EdgeColorEnd.GetElement(2);

        double red = redStart + (redEnd - redStart) * colorFactor;
        double green = greenStart + (greenEnd - greenStart) * colorFactor;
        double blue = blueStart + (blueEnd - blueStart) * colorFactor;

        actor->GetProperty()->SetColor(red, green, blue);

        if (vectorOfEdgeFilterBools[i])
        {
          m_NetworkAssembly->AddPart(actor);
        }
      }
    }
    else if (m_ChosenRenderingScheme == connectomicsRenderingVTKScheme)
    {
      vtkSmartPointer<vtkMutableUndirectedGraph> graph = vtkSmartPointer<vtkMutableUndirectedGraph>::New();

      std::vector<vtkIdType> networkToVTKvector;
      networkToVTKvector.resize(vectorOfNodes.size());

      for (unsigned int i = 0; i < vectorOfNodes.size(); i++)
      {
        networkToVTKvector[vectorOfNodes[i].id] = graph->AddVertex();
      }

      for (unsigned int i = 0; i < vectorOfEdges.size(); i++)
      {
        graph->AddEdge(networkToVTKvector[vectorOfEdges[i].first.first.id],
                       networkToVTKvector[vectorOfEdges[i].first.second.id]);
      }

      vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
      for (unsigned int i = 0; i < vectorOfNodes.size(); i++)
      {
        double x = vectorOfNodes[i].coordinates[0];
        double y = vectorOfNodes[i].coordinates[1];
        double z = vectorOfNodes[i].coordinates[2];
        points->InsertNextPoint(x, y, z);
      }

      graph->SetPoints(points);

      vtkGraphLayout *layout = vtkGraphLayout::New();
      layout->SetInputData(graph);
      vtkPassThroughLayoutStrategy *ptls = vtkPassThroughLayoutStrategy::New();
      layout->SetLayoutStrategy(ptls);

      vtkGraphToPolyData *graphToPoly = vtkGraphToPolyData::New();
      graphToPoly->SetInputConnection(layout->GetOutputPort());

      // Create the standard VTK polydata mapper and actor
      // for the connections (edges) in the tree.
      vtkPolyDataMapper *edgeMapper = vtkPolyDataMapper::New();
      edgeMapper->SetInputConnection(graphToPoly->GetOutputPort());
      vtkActor *edgeActor = vtkActor::New();
      edgeActor->SetMapper(edgeMapper);
      edgeActor->GetProperty()->SetColor(0.0, 0.5, 1.0);

      // Glyph the points of the tree polydata to create
      // VTK_VERTEX cells at each vertex in the tree.
      vtkGlyph3D *vertGlyph = vtkGlyph3D::New();
      vertGlyph->SetInputConnection(0, graphToPoly->GetOutputPort());
      vtkGlyphSource2D *glyphSource = vtkGlyphSource2D::New();
      glyphSource->SetGlyphTypeToVertex();
      vertGlyph->SetInputConnection(1, glyphSource->GetOutputPort());

      // Create a mapper for the vertices, and tell the mapper
      // to use the specified color array.
      vtkPolyDataMapper *vertMapper = vtkPolyDataMapper::New();
      vertMapper->SetInputConnection(vertGlyph->GetOutputPort());
      /*if (colorArray)
        {
        vertMapper->SetScalarModeToUsePointFieldData();
        vertMapper->SelectColorArray(colorArray);
        vertMapper->SetScalarRange(colorRange);
        }*/

      // Create an actor for the vertices.  Move the actor forward
      // in the z direction so it is drawn on top of the edge actor.
      vtkActor *vertActor = vtkActor::New();
      vertActor->SetMapper(vertMapper);
      vertActor->GetProperty()->SetPointSize(5);
      vertActor->SetPosition(0, 0, 0.001);
      // vtkProp3D.h: virtual void SetPosition(double,double,double):
      // Set/Get/Add the position of the Prop3D in world coordinates.
      m_NetworkAssembly->AddPart(edgeActor);
      m_NetworkAssembly->AddPart(vertActor);
    }

    (static_cast<mitk::ConnectomicsNetwork *>(GetDataNode()->GetData()))->SetIsModified(false);
  }
}
Ejemplo n.º 29
0
void mitk::UnstructuredGridMapper2D::GenerateDataForRenderer( mitk::BaseRenderer* renderer )
{

  BaseLocalStorage *ls = m_LSH.GetLocalStorage(renderer);
  bool needGenerateData = ls->IsGenerateDataRequired( renderer, this, GetDataNode() );

  if(needGenerateData)
  {
    ls->UpdateGenerateDataTime();

    mitk::DataNode::ConstPointer node = this->GetDataNode();
    if ( node.IsNull() )
      return;

    if (!node->GetProperty(m_ScalarMode, "scalar mode"))
    {
      m_ScalarMode = mitk::VtkScalarModeProperty::New(0);
    }

    if (!node->GetProperty(m_ScalarVisibility, "scalar visibility"))
    {
      m_ScalarVisibility = mitk::BoolProperty::New(true);
    }

    if (!node->GetProperty(m_Outline, "outline polygons"))
    {
      m_Outline = mitk::BoolProperty::New(false);
    }

    if (!node->GetProperty(m_Color, "color"))
    {
      m_Color = mitk::ColorProperty::New(1.0f, 1.0f, 1.0f);
    }

    if (!node->GetProperty(m_LineWidth, "line width"))
    {
      m_LineWidth = mitk::IntProperty::New(1);
    }

  }
  mitk::BaseData::Pointer input = const_cast<mitk::BaseData*>( GetDataNode()->GetData() );
  assert( input );

  input->Update();

  if (m_VtkPointSet) m_VtkPointSet->UnRegister(0);
  m_VtkPointSet = this->GetVtkPointSet(renderer, this->GetTimestep());
  assert(m_VtkPointSet);
  m_VtkPointSet->Register(0);

  if (m_ScalarVisibility->GetValue())
  {
    mitk::DataNode::ConstPointer node = this->GetDataNode();
    mitk::TransferFunctionProperty::Pointer transferFuncProp;
    node->GetProperty(transferFuncProp, "TransferFunction", renderer);
    if (transferFuncProp.IsNotNull())
    {
      mitk::TransferFunction::Pointer tf = transferFuncProp->GetValue();
      if (m_ScalarsToColors) m_ScalarsToColors->UnRegister(0);
      m_ScalarsToColors = static_cast<vtkScalarsToColors*>(tf->GetColorTransferFunction());
      m_ScalarsToColors->Register(0);

      if (m_ScalarsToOpacity) m_ScalarsToOpacity->UnRegister(0);
      m_ScalarsToOpacity = tf->GetScalarOpacityFunction();
      m_ScalarsToOpacity->Register(0);
    }
    else
    {
      if (m_ScalarsToColors) m_ScalarsToColors->UnRegister(0);
      m_ScalarsToColors = this->GetVtkLUT(renderer);
      assert(m_ScalarsToColors);
      m_ScalarsToColors->Register(0);

      float opacity;
      node->GetOpacity(opacity, renderer);
      if (m_ScalarsToOpacity) m_ScalarsToOpacity->UnRegister(0);
      m_ScalarsToOpacity = vtkPiecewiseFunction::New();
      double range[2];
      m_VtkPointSet->GetScalarRange(range);
      m_ScalarsToOpacity->AddSegment(range[0], opacity, range[1], opacity);
    }
  }
}
const mitk::Image* mitk::DoseImageVtkMapper2D::GetInput( void )
{
  return static_cast< const mitk::Image * >( GetDataNode()->GetData() );
}