<commit_before>/*
 *  mitkFiberBundleMapper2D.cpp
 *  mitk-all
 *
 *  Created by HAL9000 on 1/17/11.
 *  Copyright 2011 __MyCompanyName__. All rights reserved.
 *
 */

#include "mitkFiberBundleMapper2D.h"
#include <mitkBaseRenderer.h>
#include "mitkFiberBundleMapper3D.h"

#include <vtkActor.h>
#include <vtkPolyDataMapper.h>
#include <vtkPlane.h>
#include <vtkPolyData.h>
//#include <vtkPropAssembly.h>

//#include <vtkPainterPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkLookupTable.h>
#include <vtkPoints.h>
#include <vtkCamera.h>
#include <vtkPolyLine.h>
#include <vtkRenderer.h>
#include <vtkCellArray.h>
#include <vtkMatrix4x4.h>

//#include <mitkGeometry3D.h>
#include <mitkPlaneGeometry.h>
#include <mitkSliceNavigationController.h>

#include <mitkShaderRepository.h>
#include <mitkShaderProperty.h>
#include <mitkStandardFileLocations.h>

mitk::FiberBundleMapper2D::FiberBundleMapper2D()
{

}

mitk::FiberBundleMapper2D::~FiberBundleMapper2D()
{
}

const mitk::FiberBundle* mitk::FiberBundleMapper2D::GetInput()
{
  return dynamic_cast<const mitk::FiberBundle * > ( GetData() );
}

void mitk::FiberBundleMapper2D::Update(mitk::BaseRenderer * renderer)
{

  if ( !this->IsVisible( renderer ) )
  {
    return;
  }

  // Calculate time step of the input data for the specified renderer (integer value)
  // this method is implemented in mitkMapper
  this->CalculateTimeStep( renderer );

  //check if updates occured in the node or on the display
  FBLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
  const DataNode *node = this->GetDataNode();
  if ( (localStorage->m_LastUpdateTime < node->GetMTime())
      || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified?
      || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) )
  {
    MITK_INFO << "UPDATE NEEDED FOR _ " << renderer->GetName();
    this->GenerateDataForRenderer( renderer );
  }

  if ((localStorage->m_LastUpdateTime < renderer->GetDisplayGeometry()->GetMTime()) ) //was the display geometry modified? e.g. zooming, panning)
  {

    this->UpdateShaderParameter(renderer);

  }

}

void mitk::FiberBundleMapper2D::UpdateShaderParameter(mitk::BaseRenderer * renderer)
{
  FBLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
  // MITK_INFO << "uSERWAAAAAAAS, da shader brauchat a poor neue zoin";
  //get information about current position of views
  mitk::SliceNavigationController::Pointer sliceContr = renderer->GetSliceNavigationController();
  mitk::PlaneGeometry::ConstPointer planeGeo = sliceContr->GetCurrentPlaneGeometry();

  //generate according cutting planes based on the view position
  float sliceN[3], planeOrigin[3];

  // since shader uses camera coordinates, transform origin and normal from worldcoordinates to cameracoordinates

  planeOrigin[0] = (float) planeGeo->GetOrigin()[0];
  planeOrigin[1] = (float) planeGeo->GetOrigin()[1];
  planeOrigin[2] = (float) planeGeo->GetOrigin()[2];

  sliceN[0] = planeGeo->GetNormal()[0];
  sliceN[1] = planeGeo->GetNormal()[1];
  sliceN[2] = planeGeo->GetNormal()[2];

  float tmp1 = planeOrigin[0] * sliceN[0];
  float tmp2 = planeOrigin[1] * sliceN[1];
  float tmp3 = planeOrigin[2] * sliceN[2];
  float d1 = tmp1 + tmp2 + tmp3; //attention, correct normalvector

  float plane1[4];
  plane1[0] = sliceN[0];
  plane1[1] = sliceN[1];
  plane1[2] = sliceN[2];
  plane1[3] = d1;

  float thickness = 2.0;
  if(!this->GetDataNode()->GetPropertyValue("Fiber2DSliceThickness",thickness))
    MITK_INFO << "FIBER2D SLICE THICKNESS PROPERTY ERROR";

  bool fiberfading = false;
  if(!this->GetDataNode()->GetPropertyValue("Fiber2DfadeEFX",fiberfading))
      MITK_INFO << "FIBER2D SLICE FADE EFX PROPERTY ERROR";

  int fiberfading_i = 1;
  if (!fiberfading)
    fiberfading_i = 0;

  localStorage->m_PointActor->GetProperty()->AddShaderVariable("slicingPlane",4, plane1);
  localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberThickness",1, &thickness);
  localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberFadingON",1,  &fiberfading_i);

}

// ALL RAW DATA FOR VISUALIZATION IS GENERATED HERE.
// vtkActors and Mappers are feeded here
void mitk::FiberBundleMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer)
{
  MITK_INFO << "FiberBundlemapper2D _ GENERATE DATA";

  //the handler of local storage gets feeded in this method with requested data for related renderwindow
  FBLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);

  //this procedure is depricated,
  //not needed after initializaton anymore
  mitk::DataNode* node = this->GetDataNode();
  if ( node == NULL )
  {
    MITK_INFO << "check DATANODE: ....[Fail] ";
    return;
  }
  ///////////////////////////////////

  mitk::FiberBundleMapper3D::Pointer FBMapper3D = dynamic_cast< mitk::FiberBundleMapper3D* > (node->GetMapper( 2 ));
  if ( FBMapper3D->GetInput() == NULL )
  {
    MITK_INFO << "check FBMapper3D Input: ....[Fail] ";
    return;
  }

  //feed local storage with data we want to visualize
//  localStorage->m_SlicedResult = FBMapper3D->GetCut(planeOrigin, planeN, cutParams);
 // localStorage->m_SlicedResult = FBMapper3D->GetVtkFBPolyDataMapper();
  localStorage->m_SlicedResult = (vtkPolyData*) FBMapper3D->getVtkFiberBundleMapper()->GetInputAsDataSet();
  //MITK_INFO << renderer->GetName() << " OutputPoints#: " << localStorage->m_SlicedResult->GetNumberOfPoints();

  vtkSmartPointer<vtkLookupTable> lut = vtkLookupTable::New();
  lut->Build();
  localStorage->m_PointMapper->SetScalarModeToUsePointFieldData();
  //m_VtkFiberDataMapperGL->SelectColorArray("FaColors");
  localStorage->m_PointMapper->SelectColorArray("ColorValues");
  localStorage->m_PointMapper->SetLookupTable(lut);  //apply the properties after the slice was set
  //this->ApplyProperties( renderer );

  //setup the camera according to the actor with zooming/panning etc.
 // this->AdjustCamera( renderer, planeGeo );

  //  feed the vtk fiber mapper with point data ...TODO do in constructor
  localStorage->m_PointMapper->SetInput(localStorage->m_SlicedResult);   // in optimized version, mapper is feeded by localStorage->m_cutter->GetOutput();
  localStorage->m_PointActor->SetMapper(localStorage->m_PointMapper);
  localStorage->m_PointActor->GetProperty()->ShadingOn();

  // Applying shading properties
  {
    //Superclass::ApplyProperties( ls->m_Actor, renderer ) ;
    // VTK Properties
    //ApplyMitkPropertiesToVtkProperty( this->GetDataNode(), ls->m_Actor->GetProperty(), renderer );
    // Shaders
    mitk::ShaderRepository::GetGlobalShaderRepository()->ApplyProperties(this->GetDataNode(),localStorage->m_PointActor,renderer, localStorage->m_LastUpdateTime);
  }

  this->UpdateShaderParameter(renderer);

  // We have been modified => save this for next Update()
  localStorage->m_LastUpdateTime.Modified();

}

vtkProp* mitk::FiberBundleMapper2D::GetVtkProp(mitk::BaseRenderer *renderer)
{

  //MITK_INFO << "FiberBundleMapper2D GetVtkProp(renderer)";
  this->Update(renderer);
  return m_LSH.GetLocalStorage(renderer)->m_PointActor;

}

void mitk::FiberBundleMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{    //add shader to datano

  //####### load shader from file #########

  QString applicationDir = QCoreApplication::applicationDirPath();
  applicationDir.append("/");

  mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false );
  mitk::ShaderRepository::Pointer shaderRepository = mitk::ShaderRepository::GetGlobalShaderRepository();

  std::string filepath = mitk::StandardFileLocations::GetInstance()->FindFile("mitkShaderFiberClipping.xml");
  if ( filepath.empty() )
{ //for windows systems
  applicationDir = QCoreApplication::applicationDirPath();
  applicationDir.append("\\..\\");
  mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false );

}

  shaderRepository->LoadShader(mitk::StandardFileLocations::GetInstance()->FindFile("mitkShaderFiberClipping.xml"));

  //####################################################################
  node->SetProperty("shader",mitk::ShaderProperty::New("mitkShaderFiberClipping"));
  mitk::ShaderRepository::GetGlobalShaderRepository()->AddDefaultProperties(node,renderer,overwrite);

  //add other parameters to propertylist
  node->AddProperty( "Fiber2DSliceThickness", mitk::FloatProperty::New(2.0f), renderer, overwrite );
  node->AddProperty( "Fiber2DfadeEFX", mitk::BoolProperty::New(true), renderer, overwrite );

  Superclass::SetDefaultProperties(node, renderer, overwrite);
}

// following methods are essential, they actually call the GetVtkProp() method
// which returns the desired actors
void mitk::FiberBundleMapper2D::MitkRenderOverlay(BaseRenderer* renderer)
{
//   MITK_INFO << "FiberBundleMapper2D MitkRenderOVerlay(renderer)";
  if ( this->IsVisible(renderer)==false )
    return;

  if ( this->GetVtkProp(renderer)->GetVisibility() )
  {
    this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer());
  }
}

void mitk::FiberBundleMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer)
{
//  MITK_INFO << "FiberBundleMapper2D MitkRenderOpaqueGeometry(renderer)";
  if ( this->IsVisible( renderer )==false )
    return;

  if ( this->GetVtkProp(renderer)->GetVisibility() )
    this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() );
}
void mitk::FiberBundleMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer)
{
//  MITK_INFO << "FiberBundleMapper2D MitkRenderTranslucentGeometry(renderer)";
  if ( this->IsVisible(renderer)==false )
    return;

  //TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???
  if ( this->GetVtkProp(renderer)->GetVisibility() )
    this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer());

}
void mitk::FiberBundleMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer)
{
//  MITK_INFO << "FiberBundleMapper2D MitkRenderVolumentricGeometry(renderer)";
  if(IsVisible(renderer)==false)
    return;

  //TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???
  if ( GetVtkProp(renderer)->GetVisibility() )
    this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer());

}

mitk::FiberBundleMapper2D::FBLocalStorage::FBLocalStorage()
{
  m_PointActor = vtkSmartPointer<vtkActor>::New();
  m_PointMapper = vtkSmartPointer<vtkPolyDataMapper>::New();

}
<commit_msg>fix includes<commit_after>/*
 *  mitkFiberBundleMapper2D.cpp
 *  mitk-all
 *
 *  Created by HAL9000 on 1/17/11.
 *  Copyright 2011 __MyCompanyName__. All rights reserved.
 *
 */

#include "mitkFiberBundleMapper2D.h"
#include <mitkBaseRenderer.h>
#include "mitkFiberBundleMapper3D.h"

#include <vtkActor.h>
#include <vtkPolyDataMapper.h>
#include <vtkPlane.h>
#include <vtkPolyData.h>
//#include <vtkPropAssembly.h>

//#include <vtkPainterPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkLookupTable.h>
#include <vtkPoints.h>
#include <vtkCamera.h>
#include <vtkPolyLine.h>
#include <vtkRenderer.h>
#include <vtkCellArray.h>
#include <vtkMatrix4x4.h>

//#include <mitkGeometry3D.h>
#include <mitkPlaneGeometry.h>
#include <mitkSliceNavigationController.h>

#include <mitkShaderRepository.h>
#include <mitkShaderProperty.h>
#include <mitkStandardFileLocations.h>

#include <QCoreApplication>

mitk::FiberBundleMapper2D::FiberBundleMapper2D()
{

}

mitk::FiberBundleMapper2D::~FiberBundleMapper2D()
{
}

const mitk::FiberBundle* mitk::FiberBundleMapper2D::GetInput()
{
  return dynamic_cast<const mitk::FiberBundle * > ( GetData() );
}

void mitk::FiberBundleMapper2D::Update(mitk::BaseRenderer * renderer)
{

  if ( !this->IsVisible( renderer ) )
  {
    return;
  }

  // Calculate time step of the input data for the specified renderer (integer value)
  // this method is implemented in mitkMapper
  this->CalculateTimeStep( renderer );

  //check if updates occured in the node or on the display
  FBLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
  const DataNode *node = this->GetDataNode();
  if ( (localStorage->m_LastUpdateTime < node->GetMTime())
      || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified?
      || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) )
  {
    MITK_INFO << "UPDATE NEEDED FOR _ " << renderer->GetName();
    this->GenerateDataForRenderer( renderer );
  }

  if ((localStorage->m_LastUpdateTime < renderer->GetDisplayGeometry()->GetMTime()) ) //was the display geometry modified? e.g. zooming, panning)
  {

    this->UpdateShaderParameter(renderer);

  }

}

void mitk::FiberBundleMapper2D::UpdateShaderParameter(mitk::BaseRenderer * renderer)
{
  FBLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
  // MITK_INFO << "uSERWAAAAAAAS, da shader brauchat a poor neue zoin";
  //get information about current position of views
  mitk::SliceNavigationController::Pointer sliceContr = renderer->GetSliceNavigationController();
  mitk::PlaneGeometry::ConstPointer planeGeo = sliceContr->GetCurrentPlaneGeometry();

  //generate according cutting planes based on the view position
  float sliceN[3], planeOrigin[3];

  // since shader uses camera coordinates, transform origin and normal from worldcoordinates to cameracoordinates

  planeOrigin[0] = (float) planeGeo->GetOrigin()[0];
  planeOrigin[1] = (float) planeGeo->GetOrigin()[1];
  planeOrigin[2] = (float) planeGeo->GetOrigin()[2];

  sliceN[0] = planeGeo->GetNormal()[0];
  sliceN[1] = planeGeo->GetNormal()[1];
  sliceN[2] = planeGeo->GetNormal()[2];

  float tmp1 = planeOrigin[0] * sliceN[0];
  float tmp2 = planeOrigin[1] * sliceN[1];
  float tmp3 = planeOrigin[2] * sliceN[2];
  float d1 = tmp1 + tmp2 + tmp3; //attention, correct normalvector

  float plane1[4];
  plane1[0] = sliceN[0];
  plane1[1] = sliceN[1];
  plane1[2] = sliceN[2];
  plane1[3] = d1;

  float thickness = 2.0;
  if(!this->GetDataNode()->GetPropertyValue("Fiber2DSliceThickness",thickness))
    MITK_INFO << "FIBER2D SLICE THICKNESS PROPERTY ERROR";

  bool fiberfading = false;
  if(!this->GetDataNode()->GetPropertyValue("Fiber2DfadeEFX",fiberfading))
      MITK_INFO << "FIBER2D SLICE FADE EFX PROPERTY ERROR";

  int fiberfading_i = 1;
  if (!fiberfading)
    fiberfading_i = 0;

  localStorage->m_PointActor->GetProperty()->AddShaderVariable("slicingPlane",4, plane1);
  localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberThickness",1, &thickness);
  localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberFadingON",1,  &fiberfading_i);

}

// ALL RAW DATA FOR VISUALIZATION IS GENERATED HERE.
// vtkActors and Mappers are feeded here
void mitk::FiberBundleMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer)
{
  MITK_INFO << "FiberBundlemapper2D _ GENERATE DATA";

  //the handler of local storage gets feeded in this method with requested data for related renderwindow
  FBLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);

  //this procedure is depricated,
  //not needed after initializaton anymore
  mitk::DataNode* node = this->GetDataNode();
  if ( node == NULL )
  {
    MITK_INFO << "check DATANODE: ....[Fail] ";
    return;
  }
  ///////////////////////////////////

  mitk::FiberBundleMapper3D::Pointer FBMapper3D = dynamic_cast< mitk::FiberBundleMapper3D* > (node->GetMapper( 2 ));
  if ( FBMapper3D->GetInput() == NULL )
  {
    MITK_INFO << "check FBMapper3D Input: ....[Fail] ";
    return;
  }

  //feed local storage with data we want to visualize
//  localStorage->m_SlicedResult = FBMapper3D->GetCut(planeOrigin, planeN, cutParams);
 // localStorage->m_SlicedResult = FBMapper3D->GetVtkFBPolyDataMapper();
  localStorage->m_SlicedResult = (vtkPolyData*) FBMapper3D->getVtkFiberBundleMapper()->GetInputAsDataSet();
  //MITK_INFO << renderer->GetName() << " OutputPoints#: " << localStorage->m_SlicedResult->GetNumberOfPoints();

  vtkSmartPointer<vtkLookupTable> lut = vtkLookupTable::New();
  lut->Build();
  localStorage->m_PointMapper->SetScalarModeToUsePointFieldData();
  //m_VtkFiberDataMapperGL->SelectColorArray("FaColors");
  localStorage->m_PointMapper->SelectColorArray("ColorValues");
  localStorage->m_PointMapper->SetLookupTable(lut);  //apply the properties after the slice was set
  //this->ApplyProperties( renderer );

  //setup the camera according to the actor with zooming/panning etc.
 // this->AdjustCamera( renderer, planeGeo );

  //  feed the vtk fiber mapper with point data ...TODO do in constructor
  localStorage->m_PointMapper->SetInput(localStorage->m_SlicedResult);   // in optimized version, mapper is feeded by localStorage->m_cutter->GetOutput();
  localStorage->m_PointActor->SetMapper(localStorage->m_PointMapper);
  localStorage->m_PointActor->GetProperty()->ShadingOn();

  // Applying shading properties
  {
    //Superclass::ApplyProperties( ls->m_Actor, renderer ) ;
    // VTK Properties
    //ApplyMitkPropertiesToVtkProperty( this->GetDataNode(), ls->m_Actor->GetProperty(), renderer );
    // Shaders
    mitk::ShaderRepository::GetGlobalShaderRepository()->ApplyProperties(this->GetDataNode(),localStorage->m_PointActor,renderer, localStorage->m_LastUpdateTime);
  }

  this->UpdateShaderParameter(renderer);

  // We have been modified => save this for next Update()
  localStorage->m_LastUpdateTime.Modified();

}

vtkProp* mitk::FiberBundleMapper2D::GetVtkProp(mitk::BaseRenderer *renderer)
{

  //MITK_INFO << "FiberBundleMapper2D GetVtkProp(renderer)";
  this->Update(renderer);
  return m_LSH.GetLocalStorage(renderer)->m_PointActor;

}

void mitk::FiberBundleMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{    //add shader to datano

  //####### load shader from file #########

  QString applicationDir = QCoreApplication::applicationDirPath();
  MITK_INFO << QCoreApplication::applicationDirPath().toStdString().c_str();
  applicationDir.append("/");

  mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false );
  mitk::ShaderRepository::Pointer shaderRepository = mitk::ShaderRepository::GetGlobalShaderRepository();

  std::string filepath = mitk::StandardFileLocations::GetInstance()->FindFile("mitkShaderFiberClipping.xml");
  if ( filepath.empty() )
{ //for windows systems
  applicationDir = QCoreApplication::applicationDirPath();
  applicationDir.append("\\..\\");
  mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false );

}

  shaderRepository->LoadShader(mitk::StandardFileLocations::GetInstance()->FindFile("mitkShaderFiberClipping.xml"));

  //####################################################################
  node->SetProperty("shader",mitk::ShaderProperty::New("mitkShaderFiberClipping"));
  mitk::ShaderRepository::GetGlobalShaderRepository()->AddDefaultProperties(node,renderer,overwrite);

  //add other parameters to propertylist
  node->AddProperty( "Fiber2DSliceThickness", mitk::FloatProperty::New(2.0f), renderer, overwrite );
  node->AddProperty( "Fiber2DfadeEFX", mitk::BoolProperty::New(true), renderer, overwrite );

  Superclass::SetDefaultProperties(node, renderer, overwrite);
}

// following methods are essential, they actually call the GetVtkProp() method
// which returns the desired actors
void mitk::FiberBundleMapper2D::MitkRenderOverlay(BaseRenderer* renderer)
{
//   MITK_INFO << "FiberBundleMapper2D MitkRenderOVerlay(renderer)";
  if ( this->IsVisible(renderer)==false )
    return;

  if ( this->GetVtkProp(renderer)->GetVisibility() )
  {
    this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer());
  }
}

void mitk::FiberBundleMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer)
{
//  MITK_INFO << "FiberBundleMapper2D MitkRenderOpaqueGeometry(renderer)";
  if ( this->IsVisible( renderer )==false )
    return;

  if ( this->GetVtkProp(renderer)->GetVisibility() )
    this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() );
}
void mitk::FiberBundleMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer)
{
//  MITK_INFO << "FiberBundleMapper2D MitkRenderTranslucentGeometry(renderer)";
  if ( this->IsVisible(renderer)==false )
    return;

  //TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???
  if ( this->GetVtkProp(renderer)->GetVisibility() )
    this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer());

}
void mitk::FiberBundleMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer)
{
//  MITK_INFO << "FiberBundleMapper2D MitkRenderVolumentricGeometry(renderer)";
  if(IsVisible(renderer)==false)
    return;

  //TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???
  if ( GetVtkProp(renderer)->GetVisibility() )
    this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer());

}

mitk::FiberBundleMapper2D::FBLocalStorage::FBLocalStorage()
{
  m_PointActor = vtkSmartPointer<vtkActor>::New();
  m_PointMapper = vtkSmartPointer<vtkPolyDataMapper>::New();

}
<|endoftext|>


<commit_before>/*
 *  mitkFiberBundleMapper2D.cpp
 *  mitk-all
 *
 *  Created by HAL9000 on 1/17/11.
 *  Copyright 2011 __MyCompanyName__. All rights reserved.
 *
 */

#include "mitkFiberBundleMapper2D.h"
#include <mitkBaseRenderer.h>
#include "mitkFiberBundleMapper3D.h"

#include <vtkActor.h>
#include <vtkPolyDataMapper.h>
#include <vtkPlane.h>
#include <vtkPolyData.h>
//#include <vtkPropAssembly.h>

//#include <vtkPainterPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkLookupTable.h>
#include <vtkPoints.h>
#include <vtkCamera.h>
#include <vtkPolyLine.h>
#include <vtkRenderer.h>
#include <vtkCellArray.h>
#include <vtkMatrix4x4.h>

//#include <mitkGeometry3D.h>
#include <mitkPlaneGeometry.h>
#include <mitkSliceNavigationController.h>

#include <mitkShaderRepository.h>
#include <mitkShaderProperty.h>
#include <mitkStandardFileLocations.h>

mitk::FiberBundleMapper2D::FiberBundleMapper2D()
{

}

mitk::FiberBundleMapper2D::~FiberBundleMapper2D()
{
}

const mitk::FiberBundle* mitk::FiberBundleMapper2D::GetInput()
{
  return dynamic_cast<const mitk::FiberBundle * > ( GetData() );
}

void mitk::FiberBundleMapper2D::Update(mitk::BaseRenderer * renderer)
{

  if ( !this->IsVisible( renderer ) )
  {
    return;
  }

  // Calculate time step of the input data for the specified renderer (integer value)
  // this method is implemented in mitkMapper
  this->CalculateTimeStep( renderer );

  //check if updates occured in the node or on the display
  FBLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
  const DataNode *node = this->GetDataNode();
  if ( (localStorage->m_LastUpdateTime < node->GetMTime())
      || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified?
      || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) )
  {
    MITK_INFO << "UPDATE NEEDED FOR _ " << renderer->GetName();
    this->GenerateDataForRenderer( renderer );
  }

  if ((localStorage->m_LastUpdateTime < renderer->GetDisplayGeometry()->GetMTime()) ) //was the display geometry modified? e.g. zooming, panning)
  {

    this->UpdateShaderParameter(renderer);

  }

}

void mitk::FiberBundleMapper2D::UpdateShaderParameter(mitk::BaseRenderer * renderer)
{
  FBLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
  // MITK_INFO << "uSERWAAAAAAAS, da shader brauchat a poor neue zoin";
  //get information about current position of views
  mitk::SliceNavigationController::Pointer sliceContr = renderer->GetSliceNavigationController();
  mitk::PlaneGeometry::ConstPointer planeGeo = sliceContr->GetCurrentPlaneGeometry();

  //generate according cutting planes based on the view position
  float sliceN[3], planeOrigin[3];

  // since shader uses camera coordinates, transform origin and normal from worldcoordinates to cameracoordinates

  planeOrigin[0] = (float) planeGeo->GetOrigin()[0];
  planeOrigin[1] = (float) planeGeo->GetOrigin()[1];
  planeOrigin[2] = (float) planeGeo->GetOrigin()[2];

  sliceN[0] = planeGeo->GetNormal()[0];
  sliceN[1] = planeGeo->GetNormal()[1];
  sliceN[2] = planeGeo->GetNormal()[2];

  float tmp1 = planeOrigin[0] * sliceN[0];
  float tmp2 = planeOrigin[1] * sliceN[1];
  float tmp3 = planeOrigin[2] * sliceN[2];
  float d1 = tmp1 + tmp2 + tmp3; //attention, correct normalvector

  float plane1[4];
  plane1[0] = sliceN[0];
  plane1[1] = sliceN[1];
  plane1[2] = sliceN[2];
  plane1[3] = d1;

  float thickness = 2.0;
  if(!this->GetDataNode()->GetPropertyValue("Fiber2DSliceThickness",thickness))
    MITK_INFO << "FIBER2D SLICE THICKNESS PROPERTY ERROR";

  bool fiberfading = false;
  if(!this->GetDataNode()->GetPropertyValue("Fiber2DfadeEFX",fiberfading))
      MITK_INFO << "FIBER2D SLICE FADE EFX PROPERTY ERROR";

  int fiberfading_i = 1;
  if (!fiberfading)
    fiberfading_i = 0;

  localStorage->m_PointActor->GetProperty()->AddShaderVariable("slicingPlane",4, plane1);
  localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberThickness",1, &thickness);
  localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberFadingON",1,  &fiberfading_i);

}

// ALL RAW DATA FOR VISUALIZATION IS GENERATED HERE.
// vtkActors and Mappers are feeded here
void mitk::FiberBundleMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer)
{
  MITK_INFO << "FiberBundlemapper2D _ GENERATE DATA";

  //the handler of local storage gets feeded in this method with requested data for related renderwindow
  FBLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);

  //this procedure is depricated,
  //not needed after initializaton anymore
  mitk::DataNode* node = this->GetDataNode();
  if ( node == NULL )
  {
    MITK_INFO << "check DATANODE: ....[Fail] ";
    return;
  }
  ///////////////////////////////////

  mitk::FiberBundleMapper3D::Pointer FBMapper3D = dynamic_cast< mitk::FiberBundleMapper3D* > (node->GetMapper( 2 ));
  if ( FBMapper3D->GetInput() == NULL )
  {
    MITK_INFO << "check FBMapper3D Input: ....[Fail] ";
    return;
  }

  //feed local storage with data we want to visualize
//  localStorage->m_SlicedResult = FBMapper3D->GetCut(planeOrigin, planeN, cutParams);
 // localStorage->m_SlicedResult = FBMapper3D->GetVtkFBPolyDataMapper();
  localStorage->m_SlicedResult = (vtkPolyData*) FBMapper3D->getVtkFiberBundleMapper()->GetInputAsDataSet();
  //MITK_INFO << renderer->GetName() << " OutputPoints#: " << localStorage->m_SlicedResult->GetNumberOfPoints();

  vtkSmartPointer<vtkLookupTable> lut = vtkLookupTable::New();
  lut->Build();
  localStorage->m_PointMapper->SetScalarModeToUsePointFieldData();
  //m_VtkFiberDataMapperGL->SelectColorArray("FaColors");
  localStorage->m_PointMapper->SelectColorArray("ColorValues");
  localStorage->m_PointMapper->SetLookupTable(lut);  //apply the properties after the slice was set
  //this->ApplyProperties( renderer );

  //setup the camera according to the actor with zooming/panning etc.
 // this->AdjustCamera( renderer, planeGeo );

  //  feed the vtk fiber mapper with point data ...TODO do in constructor
  localStorage->m_PointMapper->SetInput(localStorage->m_SlicedResult);   // in optimized version, mapper is feeded by localStorage->m_cutter->GetOutput();
  localStorage->m_PointActor->SetMapper(localStorage->m_PointMapper);
  localStorage->m_PointActor->GetProperty()->ShadingOn();

  // Applying shading properties
  {
    //Superclass::ApplyProperties( ls->m_Actor, renderer ) ;
    // VTK Properties
    //ApplyMitkPropertiesToVtkProperty( this->GetDataNode(), ls->m_Actor->GetProperty(), renderer );
    // Shaders
    mitk::ShaderRepository::GetGlobalShaderRepository()->ApplyProperties(this->GetDataNode(),localStorage->m_PointActor,renderer, localStorage->m_LastUpdateTime);
  }

  this->UpdateShaderParameter(renderer);

  // We have been modified => save this for next Update()
  localStorage->m_LastUpdateTime.Modified();

}

vtkProp* mitk::FiberBundleMapper2D::GetVtkProp(mitk::BaseRenderer *renderer)
{

  //MITK_INFO << "FiberBundleMapper2D GetVtkProp(renderer)";
  this->Update(renderer);
  return m_LSH.GetLocalStorage(renderer)->m_PointActor;

}

void mitk::FiberBundleMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{    //add shader to datano

  //####### load shader from file #########

  QString applicationDir = QCoreApplication::applicationDirPath();
  MITK_INFO << QCoreApplication::applicationDirPath().toStdString().c_str();

    applicationDir.append("/");

  MITK_INFO << applicationDir.toStdString().c_str();
  mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false );
  mitk::ShaderRepository::Pointer shaderRepository = mitk::ShaderRepository::GetGlobalShaderRepository();

  std::string filepath = mitk::StandardFileLocations::GetInstance()->FindFile("mitkShaderFiberClipping.xml");
  if ( filepath.empty() )
{
  applicationDir = QCoreApplication::applicationDirPath();
  applicationDir.append("\\..\\");
  MITK_INFO << "WINWAS";

  QString lutPath(applicationDir);
  MITK_INFO << applicationDir.toStdString().c_str();
  mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false );

}

  shaderRepository->LoadShader(mitk::StandardFileLocations::GetInstance()->FindFile("mitkShaderFiberClipping.xml"));

  //####################################################################
  node->SetProperty("shader",mitk::ShaderProperty::New("mitkShaderFiberClipping"));
  mitk::ShaderRepository::GetGlobalShaderRepository()->AddDefaultProperties(node,renderer,overwrite);

  //add other parameters to propertylist
  node->AddProperty( "Fiber2DSliceThickness", mitk::FloatProperty::New(2.0f), renderer, overwrite );
  node->AddProperty( "Fiber2DfadeEFX", mitk::BoolProperty::New(true), renderer, overwrite );

  Superclass::SetDefaultProperties(node, renderer, overwrite);
}

// following methods are essential, they actually call the GetVtkProp() method
// which returns the desired actors
void mitk::FiberBundleMapper2D::MitkRenderOverlay(BaseRenderer* renderer)
{
//   MITK_INFO << "FiberBundleMapper2D MitkRenderOVerlay(renderer)";
  if ( this->IsVisible(renderer)==false )
    return;

  if ( this->GetVtkProp(renderer)->GetVisibility() )
  {
    this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer());
  }
}

void mitk::FiberBundleMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer)
{
//  MITK_INFO << "FiberBundleMapper2D MitkRenderOpaqueGeometry(renderer)";
  if ( this->IsVisible( renderer )==false )
    return;

  if ( this->GetVtkProp(renderer)->GetVisibility() )
    this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() );
}
void mitk::FiberBundleMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer)
{
//  MITK_INFO << "FiberBundleMapper2D MitkRenderTranslucentGeometry(renderer)";
  if ( this->IsVisible(renderer)==false )
    return;

  //TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???
  if ( this->GetVtkProp(renderer)->GetVisibility() )
    this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer());

}
void mitk::FiberBundleMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer)
{
//  MITK_INFO << "FiberBundleMapper2D MitkRenderVolumentricGeometry(renderer)";
  if(IsVisible(renderer)==false)
    return;

  //TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???
  if ( GetVtkProp(renderer)->GetVisibility() )
    this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer());

}

mitk::FiberBundleMapper2D::FBLocalStorage::FBLocalStorage()
{
  m_PointActor = vtkSmartPointer<vtkActor>::New();
  m_PointMapper = vtkSmartPointer<vtkPolyDataMapper>::New();

}
<commit_msg>first version of adapting path<commit_after>/*
 *  mitkFiberBundleMapper2D.cpp
 *  mitk-all
 *
 *  Created by HAL9000 on 1/17/11.
 *  Copyright 2011 __MyCompanyName__. All rights reserved.
 *
 */

#include "mitkFiberBundleMapper2D.h"
#include <mitkBaseRenderer.h>
#include "mitkFiberBundleMapper3D.h"

#include <vtkActor.h>
#include <vtkPolyDataMapper.h>
#include <vtkPlane.h>
#include <vtkPolyData.h>
//#include <vtkPropAssembly.h>

//#include <vtkPainterPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkLookupTable.h>
#include <vtkPoints.h>
#include <vtkCamera.h>
#include <vtkPolyLine.h>
#include <vtkRenderer.h>
#include <vtkCellArray.h>
#include <vtkMatrix4x4.h>

//#include <mitkGeometry3D.h>
#include <mitkPlaneGeometry.h>
#include <mitkSliceNavigationController.h>

#include <mitkShaderRepository.h>
#include <mitkShaderProperty.h>
#include <mitkStandardFileLocations.h>

mitk::FiberBundleMapper2D::FiberBundleMapper2D()
{

}

mitk::FiberBundleMapper2D::~FiberBundleMapper2D()
{
}

const mitk::FiberBundle* mitk::FiberBundleMapper2D::GetInput()
{
  return dynamic_cast<const mitk::FiberBundle * > ( GetData() );
}

void mitk::FiberBundleMapper2D::Update(mitk::BaseRenderer * renderer)
{

  if ( !this->IsVisible( renderer ) )
  {
    return;
  }

  // Calculate time step of the input data for the specified renderer (integer value)
  // this method is implemented in mitkMapper
  this->CalculateTimeStep( renderer );

  //check if updates occured in the node or on the display
  FBLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
  const DataNode *node = this->GetDataNode();
  if ( (localStorage->m_LastUpdateTime < node->GetMTime())
      || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified?
      || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) )
  {
    MITK_INFO << "UPDATE NEEDED FOR _ " << renderer->GetName();
    this->GenerateDataForRenderer( renderer );
  }

  if ((localStorage->m_LastUpdateTime < renderer->GetDisplayGeometry()->GetMTime()) ) //was the display geometry modified? e.g. zooming, panning)
  {

    this->UpdateShaderParameter(renderer);

  }

}

void mitk::FiberBundleMapper2D::UpdateShaderParameter(mitk::BaseRenderer * renderer)
{
  FBLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
  // MITK_INFO << "uSERWAAAAAAAS, da shader brauchat a poor neue zoin";
  //get information about current position of views
  mitk::SliceNavigationController::Pointer sliceContr = renderer->GetSliceNavigationController();
  mitk::PlaneGeometry::ConstPointer planeGeo = sliceContr->GetCurrentPlaneGeometry();

  //generate according cutting planes based on the view position
  float sliceN[3], planeOrigin[3];

  // since shader uses camera coordinates, transform origin and normal from worldcoordinates to cameracoordinates

  planeOrigin[0] = (float) planeGeo->GetOrigin()[0];
  planeOrigin[1] = (float) planeGeo->GetOrigin()[1];
  planeOrigin[2] = (float) planeGeo->GetOrigin()[2];

  sliceN[0] = planeGeo->GetNormal()[0];
  sliceN[1] = planeGeo->GetNormal()[1];
  sliceN[2] = planeGeo->GetNormal()[2];

  float tmp1 = planeOrigin[0] * sliceN[0];
  float tmp2 = planeOrigin[1] * sliceN[1];
  float tmp3 = planeOrigin[2] * sliceN[2];
  float d1 = tmp1 + tmp2 + tmp3; //attention, correct normalvector

  float plane1[4];
  plane1[0] = sliceN[0];
  plane1[1] = sliceN[1];
  plane1[2] = sliceN[2];
  plane1[3] = d1;

  float thickness = 2.0;
  if(!this->GetDataNode()->GetPropertyValue("Fiber2DSliceThickness",thickness))
    MITK_INFO << "FIBER2D SLICE THICKNESS PROPERTY ERROR";

  bool fiberfading = false;
  if(!this->GetDataNode()->GetPropertyValue("Fiber2DfadeEFX",fiberfading))
      MITK_INFO << "FIBER2D SLICE FADE EFX PROPERTY ERROR";

  int fiberfading_i = 1;
  if (!fiberfading)
    fiberfading_i = 0;

  localStorage->m_PointActor->GetProperty()->AddShaderVariable("slicingPlane",4, plane1);
  localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberThickness",1, &thickness);
  localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberFadingON",1,  &fiberfading_i);

}

// ALL RAW DATA FOR VISUALIZATION IS GENERATED HERE.
// vtkActors and Mappers are feeded here
void mitk::FiberBundleMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer)
{
  MITK_INFO << "FiberBundlemapper2D _ GENERATE DATA";

  //the handler of local storage gets feeded in this method with requested data for related renderwindow
  FBLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);

  //this procedure is depricated,
  //not needed after initializaton anymore
  mitk::DataNode* node = this->GetDataNode();
  if ( node == NULL )
  {
    MITK_INFO << "check DATANODE: ....[Fail] ";
    return;
  }
  ///////////////////////////////////

  mitk::FiberBundleMapper3D::Pointer FBMapper3D = dynamic_cast< mitk::FiberBundleMapper3D* > (node->GetMapper( 2 ));
  if ( FBMapper3D->GetInput() == NULL )
  {
    MITK_INFO << "check FBMapper3D Input: ....[Fail] ";
    return;
  }

  //feed local storage with data we want to visualize
//  localStorage->m_SlicedResult = FBMapper3D->GetCut(planeOrigin, planeN, cutParams);
 // localStorage->m_SlicedResult = FBMapper3D->GetVtkFBPolyDataMapper();
  localStorage->m_SlicedResult = (vtkPolyData*) FBMapper3D->getVtkFiberBundleMapper()->GetInputAsDataSet();
  //MITK_INFO << renderer->GetName() << " OutputPoints#: " << localStorage->m_SlicedResult->GetNumberOfPoints();

  vtkSmartPointer<vtkLookupTable> lut = vtkLookupTable::New();
  lut->Build();
  localStorage->m_PointMapper->SetScalarModeToUsePointFieldData();
  //m_VtkFiberDataMapperGL->SelectColorArray("FaColors");
  localStorage->m_PointMapper->SelectColorArray("ColorValues");
  localStorage->m_PointMapper->SetLookupTable(lut);  //apply the properties after the slice was set
  //this->ApplyProperties( renderer );

  //setup the camera according to the actor with zooming/panning etc.
 // this->AdjustCamera( renderer, planeGeo );

  //  feed the vtk fiber mapper with point data ...TODO do in constructor
  localStorage->m_PointMapper->SetInput(localStorage->m_SlicedResult);   // in optimized version, mapper is feeded by localStorage->m_cutter->GetOutput();
  localStorage->m_PointActor->SetMapper(localStorage->m_PointMapper);
  localStorage->m_PointActor->GetProperty()->ShadingOn();

  // Applying shading properties
  {
    //Superclass::ApplyProperties( ls->m_Actor, renderer ) ;
    // VTK Properties
    //ApplyMitkPropertiesToVtkProperty( this->GetDataNode(), ls->m_Actor->GetProperty(), renderer );
    // Shaders
    mitk::ShaderRepository::GetGlobalShaderRepository()->ApplyProperties(this->GetDataNode(),localStorage->m_PointActor,renderer, localStorage->m_LastUpdateTime);
  }

  this->UpdateShaderParameter(renderer);

  // We have been modified => save this for next Update()
  localStorage->m_LastUpdateTime.Modified();

}

vtkProp* mitk::FiberBundleMapper2D::GetVtkProp(mitk::BaseRenderer *renderer)
{

  //MITK_INFO << "FiberBundleMapper2D GetVtkProp(renderer)";
  this->Update(renderer);
  return m_LSH.GetLocalStorage(renderer)->m_PointActor;

}

void mitk::FiberBundleMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{    //add shader to datano

  //####### load shader from file #########

  QString applicationDir = QCoreApplication::applicationDirPath();
  applicationDir.append("/");

  mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false );
  mitk::ShaderRepository::Pointer shaderRepository = mitk::ShaderRepository::GetGlobalShaderRepository();

  std::string filepath = mitk::StandardFileLocations::GetInstance()->FindFile("mitkShaderFiberClipping.xml");
  if ( filepath.empty() )
{ //for windows systems
  applicationDir = QCoreApplication::applicationDirPath();
  applicationDir.append("\\..\\");
  mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false );

}

  shaderRepository->LoadShader(mitk::StandardFileLocations::GetInstance()->FindFile("mitkShaderFiberClipping.xml"));

  //####################################################################
  node->SetProperty("shader",mitk::ShaderProperty::New("mitkShaderFiberClipping"));
  mitk::ShaderRepository::GetGlobalShaderRepository()->AddDefaultProperties(node,renderer,overwrite);

  //add other parameters to propertylist
  node->AddProperty( "Fiber2DSliceThickness", mitk::FloatProperty::New(2.0f), renderer, overwrite );
  node->AddProperty( "Fiber2DfadeEFX", mitk::BoolProperty::New(true), renderer, overwrite );

  Superclass::SetDefaultProperties(node, renderer, overwrite);
}

// following methods are essential, they actually call the GetVtkProp() method
// which returns the desired actors
void mitk::FiberBundleMapper2D::MitkRenderOverlay(BaseRenderer* renderer)
{
//   MITK_INFO << "FiberBundleMapper2D MitkRenderOVerlay(renderer)";
  if ( this->IsVisible(renderer)==false )
    return;

  if ( this->GetVtkProp(renderer)->GetVisibility() )
  {
    this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer());
  }
}

void mitk::FiberBundleMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer)
{
//  MITK_INFO << "FiberBundleMapper2D MitkRenderOpaqueGeometry(renderer)";
  if ( this->IsVisible( renderer )==false )
    return;

  if ( this->GetVtkProp(renderer)->GetVisibility() )
    this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() );
}
void mitk::FiberBundleMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer)
{
//  MITK_INFO << "FiberBundleMapper2D MitkRenderTranslucentGeometry(renderer)";
  if ( this->IsVisible(renderer)==false )
    return;

  //TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???
  if ( this->GetVtkProp(renderer)->GetVisibility() )
    this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer());

}
void mitk::FiberBundleMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer)
{
//  MITK_INFO << "FiberBundleMapper2D MitkRenderVolumentricGeometry(renderer)";
  if(IsVisible(renderer)==false)
    return;

  //TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???
  if ( GetVtkProp(renderer)->GetVisibility() )
    this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer());

}

mitk::FiberBundleMapper2D::FBLocalStorage::FBLocalStorage()
{
  m_PointActor = vtkSmartPointer<vtkActor>::New();
  m_PointMapper = vtkSmartPointer<vtkPolyDataMapper>::New();

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: itrform2.hxx,v $
 * $Revision: 1.18 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _ITRFORM2_HXX
#define _ITRFORM2_HXX
#include "itrpaint.hxx"

class SwFlyCntPortion;
class SwInterHyphInfo;
class SwDropPortion;
class SwFmtDrop;
class SwTxtAttr;
class SwNumberPortion;
class SwErgoSumPortion;
class SwExpandPortion;
class SwMultiPortion;
class SwFtnPortion;
class SvLongs;

/*************************************************************************
 *                      class SwTxtFormatter
 *************************************************************************/

class SwTxtFormatter : public SwTxtPainter
{
    const SwFmtDrop *pDropFmt;
    SwMultiPortion* pMulti; // during formatting a multi-portion
    sal_uInt8 nCntEndHyph;  // zaehlt aufeinanderfolgende Hyphens am Zeilenende
    sal_uInt8 nCntMidHyph;  // zaehlt aufeinanderfolgende Hyphens vor Flies
    xub_StrLen nLeftScanIdx; // for increasing performance during
    xub_StrLen nRightScanIdx;     // scanning for portion ends
    sal_Bool bOnceMore : 1; // noch 'ne Runde?
    sal_Bool bFlyInCntBase : 1; // Base-Referenz der zeichengeb. Rahmen setzen
    sal_Bool bChanges : 1; // Flag, fuer die Berechnung des Repaint-Rechtecks
    sal_Bool bTruncLines : 1; // Flag, Repaint-Rechtecks ggf. erweitern
    sal_Bool bUnclipped : 1; // Flag, ob Repaint groesser als feste Zeilenhoehe
    SwLinePortion *NewPortion( SwTxtFormatInfo &rInf );
    SwTxtPortion  *NewTxtPortion( SwTxtFormatInfo &rInf );
    SwLinePortion *NewExtraPortion( SwTxtFormatInfo &rInf );
    SwTabPortion *NewTabPortion( SwTxtFormatInfo &rInf, bool bAuto ) const;
    SwNumberPortion *NewNumberPortion( SwTxtFormatInfo &rInf ) const;
    SwDropPortion *NewDropPortion( SwTxtFormatInfo &rInf );
    SwNumberPortion *NewFtnNumPortion( SwTxtFormatInfo &rInf ) const;
    SwErgoSumPortion *NewErgoSumPortion( SwTxtFormatInfo &rInf ) const;
    SwExpandPortion *NewFldPortion( SwTxtFormatInfo &rInf,
                                    const SwTxtAttr *pHt ) const;
    SwFtnPortion *NewFtnPortion( SwTxtFormatInfo &rInf, SwTxtAttr *pHt );
    SwFlyCntPortion *NewFlyCntPortion( SwTxtFormatInfo &rInf,
                                       SwTxtAttr *pHt ) const;
    SwLinePortion *WhichFirstPortion( SwTxtFormatInfo &rInf );
    SwTxtPortion *WhichTxtPor( SwTxtFormatInfo &rInf ) const;

    // Das Herzstueck der Formatierung
    void BuildPortions( SwTxtFormatInfo &rInf );
    BOOL BuildMultiPortion( SwTxtFormatInfo &rInf, SwMultiPortion& rMulti );

    // Berechnung des emulierten rechten Rands
    void CalcFlyWidth( SwTxtFormatInfo &rInf );

    // wird von SwTxtFormatter wegen UpdatePos ueberladen
    void CalcAdjustLine( SwLineLayout *pCurr );

    // consideres line spacing attributes
    void CalcRealHeight( sal_Bool bNewLine = sal_False );

    // uebertraegt die Daten nach rInf
    void FeedInf( SwTxtFormatInfo &rInf ) const;

    // behandelt die Unterlaufsituationen
    SwLinePortion *UnderFlow( SwTxtFormatInfo &rInf );

    // errechnet den Ascent und die Hoehe aus der Fontmetric
    void CalcAscent( SwTxtFormatInfo &rInf, SwLinePortion *pPor );

    // determines, if a optimized repaint rectange is allowed
    sal_Bool AllowRepaintOpt() const;

    // calculates and sets the optimized repaint offset
    long CalcOptRepaint( xub_StrLen nOldLineEnd, const SvLongs* pFlyStart );

    // wird von FormatLine gerufen.
    void FormatReset( SwTxtFormatInfo &rInf );

    // durch das Adjustment aendert sich die Position der Portions
    void UpdatePos( SwLineLayout *pCurr, Point aStart, xub_StrLen nStartIdx,
            sal_Bool bAllWays = sal_False ) const;

    // Setze alle FlyInCntFrms auf die uebergebene BaseLine
    void AlignFlyInCntBase( long nBaseLine ) const;

    // Unterlaufbedingungen bei Flys
    sal_Bool ChkFlyUnderflow( SwTxtFormatInfo &rInf ) const;

    // Portion einfuegen.
    void InsertPortion( SwTxtFormatInfo &rInf, SwLinePortion *pPor ) const;

    // schaetzt die Hoehe fuer die DropPortion
    void GuessDropHeight( const MSHORT nLines );

public:
    // errechnet die Hoehe fuer die DropPortion
    void CalcDropHeight( const MSHORT nLines );

    // errechnet den Bottom des Absatzes, beruecksichtigt an diesem verankerte
    // Objekte mit Umlauf 1. Absatz.
    SwTwips CalcBottomLine() const;

    // Beruecksichtigt zeichengebundene Objekte bei der Repaintrechteck-
    // berechnung in Zeilen mit fester Zeilenhoehe
    void CalcUnclipped( SwTwips& rTop, SwTwips& rBottom );

    // u.a. fuer DropCaps
    sal_Bool CalcOnceMore();

    void CtorInitTxtFormatter( SwTxtFrm *pFrm, SwTxtFormatInfo *pInf );
    inline SwTxtFormatter( SwTxtFrm *pTxtFrm, SwTxtFormatInfo *pTxtFmtInf )
           { CtorInitTxtFormatter( pTxtFrm, pTxtFmtInf ); }
    ~SwTxtFormatter();

    xub_StrLen FormatLine( const xub_StrLen nStart );

    void RecalcRealHeight();

    // Wir formatieren eine Zeile fuer die interaktive Trennung
    sal_Bool Hyphenate( SwInterHyphInfo &rInf );

    // Spezialmethode fuer QuoVadis-Texte
    // nErgo ist die Seitennummer der ErgoSum-Ftn
    // Bei 0 ist es noch unklar.
    xub_StrLen FormatQuoVadis( const xub_StrLen nStart );

    // Die Notbremse: Formatierung abbrechen, Zeile verwerfen.
    inline sal_Bool IsStop() const { return GetInfo().IsStop(); }

    // Das Gegenstueck: Formatierung unbedingt fortsetzen.
    inline sal_Bool IsNewLine() const { return GetInfo().IsNewLine(); }

    // FormatQuick(); auffrischen von Formatinformationen
    inline sal_Bool IsQuick() const { return GetInfo().IsQuick(); }

    // erzeugt ggfs. ein SwLineLayout, dass Ftn/Fly--Oszillation unterbindet.
    void MakeDummyLine();

    // SwTxtIter-Funktionalitaet
    void Insert( SwLineLayout *pLine );

    // die noch verbleibende Hoehe bis zum Seitenrand
    KSHORT GetFrmRstHeight() const;

    // Wie breit waerest Du ohne rechte Begrenzungen (Flys etc.)?
    SwTwips _CalcFitToContent( );

    SwLinePortion* MakeRestPortion(const SwLineLayout* pLine, xub_StrLen nPos);

    inline const SwFmtDrop *GetDropFmt() const { return pDropFmt; }
    inline void ClearDropFmt() { pDropFmt = 0; }

    inline SwMultiPortion *GetMulti() const { return pMulti; }

    inline const sal_Bool IsOnceMore() const { return bOnceMore; }
    inline void       SetOnceMore( sal_Bool bNew ) { bOnceMore = bNew; }

    inline const sal_Bool HasChanges() const { return bChanges; }
    inline void       SetChanges()       { bChanges = sal_True; }

    inline const sal_Bool HasTruncLines() const { return bTruncLines; }
    inline void       SetTruncLines( sal_Bool bNew ) { bTruncLines = bNew; }

    inline const sal_Bool IsUnclipped() const { return bUnclipped; }
    inline void       SetUnclipped( sal_Bool bNew ) { bUnclipped = bNew; }

    inline const sal_Bool IsFlyInCntBase() const { return bFlyInCntBase; }
    inline void  SetFlyInCntBase( sal_Bool bNew = sal_True ){ bFlyInCntBase = bNew; }

    inline SwTxtFormatInfo &GetInfo()
        { return (SwTxtFormatInfo&)SwTxtIter::GetInfo(); }
    inline const SwTxtFormatInfo &GetInfo() const
        { return (const SwTxtFormatInfo&)SwTxtIter::GetInfo(); }

    inline void InitCntHyph() { CntHyphens( nCntEndHyph, nCntMidHyph ); }
    inline const sal_uInt8 &CntEndHyph() const { return nCntEndHyph; }
    inline const sal_uInt8 &CntMidHyph() const { return nCntMidHyph; }
    inline sal_uInt8 &CntEndHyph() { return nCntEndHyph; }
    inline sal_uInt8 &CntMidHyph() { return nCntMidHyph; }
};

#endif
<commit_msg>INTEGRATION: CWS swenhancedfields2 (1.17.232); FILE MERGED 2008/08/04 14:17:50 b_michaelsen 1.17.232.2: RESYNC: (1.17-1.18); FILE MERGED 2008/04/23 14:29:18 ama 1.17.232.1: #i33737#: Enhanced fields<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: itrform2.hxx,v $
 * $Revision: 1.19 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _ITRFORM2_HXX
#define _ITRFORM2_HXX
#include "itrpaint.hxx"

class SwFlyCntPortion;
class SwInterHyphInfo;
class SwDropPortion;
class SwFmtDrop;
class SwTxtAttr;
class SwNumberPortion;
class SwErgoSumPortion;
class SwExpandPortion;
class SwMultiPortion;
class SwFtnPortion;
class SvLongs;

/*************************************************************************
 *                      class SwTxtFormatter
 *************************************************************************/

class SwTxtFormatter : public SwTxtPainter
{
    const SwFmtDrop *pDropFmt;
    SwMultiPortion* pMulti; // during formatting a multi-portion
    sal_uInt8 nCntEndHyph;  // zaehlt aufeinanderfolgende Hyphens am Zeilenende
    sal_uInt8 nCntMidHyph;  // zaehlt aufeinanderfolgende Hyphens vor Flies
    xub_StrLen nLeftScanIdx; // for increasing performance during
    xub_StrLen nRightScanIdx;     // scanning for portion ends
    sal_Bool bOnceMore : 1; // noch 'ne Runde?
    sal_Bool bFlyInCntBase : 1; // Base-Referenz der zeichengeb. Rahmen setzen
    sal_Bool bChanges : 1; // Flag, fuer die Berechnung des Repaint-Rechtecks
    sal_Bool bTruncLines : 1; // Flag, Repaint-Rechtecks ggf. erweitern
    sal_Bool bUnclipped : 1; // Flag, ob Repaint groesser als feste Zeilenhoehe
    SwLinePortion *NewPortion( SwTxtFormatInfo &rInf );
    SwTxtPortion  *NewTxtPortion( SwTxtFormatInfo &rInf );
    SwLinePortion *NewExtraPortion( SwTxtFormatInfo &rInf );
    SwTabPortion *NewTabPortion( SwTxtFormatInfo &rInf, bool bAuto ) const;
    SwNumberPortion *NewNumberPortion( SwTxtFormatInfo &rInf ) const;
    SwDropPortion *NewDropPortion( SwTxtFormatInfo &rInf );
    SwNumberPortion *NewFtnNumPortion( SwTxtFormatInfo &rInf ) const;
    SwErgoSumPortion *NewErgoSumPortion( SwTxtFormatInfo &rInf ) const;
    SwExpandPortion *NewFldPortion( SwTxtFormatInfo &rInf,
                                    const SwTxtAttr *pHt ) const;
    SwFtnPortion *NewFtnPortion( SwTxtFormatInfo &rInf, SwTxtAttr *pHt );
    SwFlyCntPortion *NewFlyCntPortion( SwTxtFormatInfo &rInf,
                                       SwTxtAttr *pHt ) const;
    SwLinePortion *WhichFirstPortion( SwTxtFormatInfo &rInf );
    SwTxtPortion *WhichTxtPor( SwTxtFormatInfo &rInf ) const;

    // Das Herzstueck der Formatierung
    void BuildPortions( SwTxtFormatInfo &rInf );
    BOOL BuildMultiPortion( SwTxtFormatInfo &rInf, SwMultiPortion& rMulti );

    // Berechnung des emulierten rechten Rands
    void CalcFlyWidth( SwTxtFormatInfo &rInf );

    // wird von SwTxtFormatter wegen UpdatePos ueberladen
    void CalcAdjustLine( SwLineLayout *pCurr );

    // consideres line spacing attributes
    void CalcRealHeight( sal_Bool bNewLine = sal_False );

    // uebertraegt die Daten nach rInf
    void FeedInf( SwTxtFormatInfo &rInf ) const;

    // behandelt die Unterlaufsituationen
    SwLinePortion *UnderFlow( SwTxtFormatInfo &rInf );

    // errechnet den Ascent und die Hoehe aus der Fontmetric
    void CalcAscent( SwTxtFormatInfo &rInf, SwLinePortion *pPor );

    // determines, if a optimized repaint rectange is allowed
    sal_Bool AllowRepaintOpt() const;

    // calculates and sets the optimized repaint offset
    long CalcOptRepaint( xub_StrLen nOldLineEnd, const SvLongs* pFlyStart );

    // wird von FormatLine gerufen.
    void FormatReset( SwTxtFormatInfo &rInf );

    // durch das Adjustment aendert sich die Position der Portions
    void UpdatePos( SwLineLayout *pCurr, Point aStart, xub_StrLen nStartIdx,
            sal_Bool bAllWays = sal_False ) const;

    // Setze alle FlyInCntFrms auf die uebergebene BaseLine
    void AlignFlyInCntBase( long nBaseLine ) const;

    // Unterlaufbedingungen bei Flys
    sal_Bool ChkFlyUnderflow( SwTxtFormatInfo &rInf ) const;

    // Portion einfuegen.
    void InsertPortion( SwTxtFormatInfo &rInf, SwLinePortion *pPor ) const;

    // schaetzt die Hoehe fuer die DropPortion
    void GuessDropHeight( const MSHORT nLines );

public:
    // errechnet die Hoehe fuer die DropPortion
    void CalcDropHeight( const MSHORT nLines );

    // errechnet den Bottom des Absatzes, beruecksichtigt an diesem verankerte
    // Objekte mit Umlauf 1. Absatz.
    SwTwips CalcBottomLine() const;

    // Beruecksichtigt zeichengebundene Objekte bei der Repaintrechteck-
    // berechnung in Zeilen mit fester Zeilenhoehe
    void CalcUnclipped( SwTwips& rTop, SwTwips& rBottom );

    // u.a. fuer DropCaps
    sal_Bool CalcOnceMore();

    void CtorInitTxtFormatter( SwTxtFrm *pFrm, SwTxtFormatInfo *pInf );
    inline SwTxtFormatter( SwTxtFrm *pTxtFrm, SwTxtFormatInfo *pTxtFmtInf ) : SwTxtPainter(pTxtFrm!=NULL?pTxtFrm->GetTxtNode():NULL)
           { CtorInitTxtFormatter( pTxtFrm, pTxtFmtInf ); }
    ~SwTxtFormatter();

    xub_StrLen FormatLine( const xub_StrLen nStart );

    void RecalcRealHeight();

    // Wir formatieren eine Zeile fuer die interaktive Trennung
    sal_Bool Hyphenate( SwInterHyphInfo &rInf );

    // Spezialmethode fuer QuoVadis-Texte
    // nErgo ist die Seitennummer der ErgoSum-Ftn
    // Bei 0 ist es noch unklar.
    xub_StrLen FormatQuoVadis( const xub_StrLen nStart );

    // Die Notbremse: Formatierung abbrechen, Zeile verwerfen.
    inline sal_Bool IsStop() const { return GetInfo().IsStop(); }

    // Das Gegenstueck: Formatierung unbedingt fortsetzen.
    inline sal_Bool IsNewLine() const { return GetInfo().IsNewLine(); }

    // FormatQuick(); auffrischen von Formatinformationen
    inline sal_Bool IsQuick() const { return GetInfo().IsQuick(); }

    // erzeugt ggfs. ein SwLineLayout, dass Ftn/Fly--Oszillation unterbindet.
    void MakeDummyLine();

    // SwTxtIter-Funktionalitaet
    void Insert( SwLineLayout *pLine );

    // die noch verbleibende Hoehe bis zum Seitenrand
    KSHORT GetFrmRstHeight() const;

    // Wie breit waerest Du ohne rechte Begrenzungen (Flys etc.)?
    SwTwips _CalcFitToContent( );

    SwLinePortion* MakeRestPortion(const SwLineLayout* pLine, xub_StrLen nPos);

    inline const SwFmtDrop *GetDropFmt() const { return pDropFmt; }
    inline void ClearDropFmt() { pDropFmt = 0; }

    inline SwMultiPortion *GetMulti() const { return pMulti; }

    inline const sal_Bool IsOnceMore() const { return bOnceMore; }
    inline void       SetOnceMore( sal_Bool bNew ) { bOnceMore = bNew; }

    inline const sal_Bool HasChanges() const { return bChanges; }
    inline void       SetChanges()       { bChanges = sal_True; }

    inline const sal_Bool HasTruncLines() const { return bTruncLines; }
    inline void       SetTruncLines( sal_Bool bNew ) { bTruncLines = bNew; }

    inline const sal_Bool IsUnclipped() const { return bUnclipped; }
    inline void       SetUnclipped( sal_Bool bNew ) { bUnclipped = bNew; }

    inline const sal_Bool IsFlyInCntBase() const { return bFlyInCntBase; }
    inline void  SetFlyInCntBase( sal_Bool bNew = sal_True ){ bFlyInCntBase = bNew; }

    inline SwTxtFormatInfo &GetInfo()
        { return (SwTxtFormatInfo&)SwTxtIter::GetInfo(); }
    inline const SwTxtFormatInfo &GetInfo() const
        { return (const SwTxtFormatInfo&)SwTxtIter::GetInfo(); }

    inline void InitCntHyph() { CntHyphens( nCntEndHyph, nCntMidHyph ); }
    inline const sal_uInt8 &CntEndHyph() const { return nCntEndHyph; }
    inline const sal_uInt8 &CntMidHyph() const { return nCntMidHyph; }
    inline sal_uInt8 &CntEndHyph() { return nCntEndHyph; }
    inline sal_uInt8 &CntMidHyph() { return nCntMidHyph; }
};

#endif
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

//MITK
#include "mitkTestingMacros.h"
#include "mitkRenderingTestHelper.h"
#include <mitkOverlayManager.h>
#include <mitkPointSet.h>

//VTK
#include <vtkRegressionTestImage.h>
#include "mitkTextOverlay2D.h"
#include "mitkOverlay2DLayouter.h"
#include "mitkLabelOverlay3D.h"

int mitkLabelOverlay3DRendering2DTest(int argc, char* argv[])
{
  // load all arguments into a datastorage, take last argument as reference rendering
  // setup a renderwindow of fixed size X*Y
  // render the datastorage
  // compare rendering to reference image
  MITK_TEST_BEGIN("mitkLabelOverlay3DRendering2DTest")

  mitk::RenderingTestHelper renderingHelper(640, 480, argc, argv);
//  renderingHelper.SetAutomaticallyCloseRenderWindow(false);

//  renderingHelper.SetAutomaticallyCloseRenderWindow(false);
  mitk::BaseRenderer* renderer = mitk::BaseRenderer::GetInstance(renderingHelper.GetVtkRenderWindow());
  mitk::OverlayManager::Pointer OverlayManager = mitk::OverlayManager::New();
  renderer->SetOverlayManager(OverlayManager);

  mitk::PointSet::Pointer pointset = mitk::PointSet::New();
  mitk::LabelOverlay3D::Pointer label3d = mitk::LabelOverlay3D::New();
  mitk::Point3D offset;
  offset[0] = .5;
  offset[1] = .5;
  offset[2] = .5;

  std::vector<std::string> labels;
  int idx = 0;
  for(int i=-10 ; i < 10 ; i+=4){
    for(int j=-10 ; j < 10 ; j+=4){
      mitk::Point3D point;
      point[0] = i;
      point[1] = j;
      point[2] = (i*j)/10;
      pointset->InsertPoint(idx++, point);
      labels.push_back("test");
    }
  }

  label3d->SetLabelCoordinates(pointset);
  label3d->SetLabelVector(labels);
  label3d->SetOffsetVector(offset);
  OverlayManager->AddOverlay(label3d.GetPointer());

  mitk::DataNode::Pointer datanode = mitk::DataNode::New();
  datanode->SetData(pointset);
  datanode->SetName("pointSet");
  renderingHelper.AddNodeToStorage(datanode);
  renderingHelper.Render();

  //### Usage of CompareRenderWindowAgainstReference: See docu of mitkRrenderingTestHelper
  MITK_TEST_CONDITION( renderingHelper.CompareRenderWindowAgainstReference(argc, argv) == true, "CompareRenderWindowAgainstReference test result positive?" );

  //use this to generate a reference screenshot or save the file:
  bool generateReferenceScreenshot = false;
  if(generateReferenceScreenshot)
  {
    renderingHelper.SaveReferenceScreenShot("/home/christoph/Pictures/RenderingTestData/mitkLabelOverlay3DRendering2DTest.png");
  }

  MITK_TEST_END();
}

<commit_msg>COMP: higher treshold for rendering test<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

//MITK
#include "mitkTestingMacros.h"
#include "mitkRenderingTestHelper.h"
#include <mitkOverlayManager.h>
#include <mitkPointSet.h>

//VTK
#include <vtkRegressionTestImage.h>
#include "mitkTextOverlay2D.h"
#include "mitkOverlay2DLayouter.h"
#include "mitkLabelOverlay3D.h"

int mitkLabelOverlay3DRendering2DTest(int argc, char* argv[])
{
  // load all arguments into a datastorage, take last argument as reference rendering
  // setup a renderwindow of fixed size X*Y
  // render the datastorage
  // compare rendering to reference image
  MITK_TEST_BEGIN("mitkLabelOverlay3DRendering2DTest")

  mitk::RenderingTestHelper renderingHelper(640, 480, argc, argv);
//  renderingHelper.SetAutomaticallyCloseRenderWindow(false);

//  renderingHelper.SetAutomaticallyCloseRenderWindow(false);
  mitk::BaseRenderer* renderer = mitk::BaseRenderer::GetInstance(renderingHelper.GetVtkRenderWindow());
  mitk::OverlayManager::Pointer OverlayManager = mitk::OverlayManager::New();
  renderer->SetOverlayManager(OverlayManager);

  mitk::PointSet::Pointer pointset = mitk::PointSet::New();
  mitk::LabelOverlay3D::Pointer label3d = mitk::LabelOverlay3D::New();
  mitk::Point3D offset;
  offset[0] = .5;
  offset[1] = .5;
  offset[2] = .5;

  std::vector<std::string> labels;
  int idx = 0;
  for(int i=-10 ; i < 10 ; i+=4){
    for(int j=-10 ; j < 10 ; j+=4){
      mitk::Point3D point;
      point[0] = i;
      point[1] = j;
      point[2] = (i*j)/10;
      pointset->InsertPoint(idx++, point);
      labels.push_back("test");
    }
  }

  label3d->SetLabelCoordinates(pointset);
  label3d->SetLabelVector(labels);
  label3d->SetOffsetVector(offset);
  OverlayManager->AddOverlay(label3d.GetPointer());

  mitk::DataNode::Pointer datanode = mitk::DataNode::New();
  datanode->SetData(pointset);
  datanode->SetName("pointSet");
  renderingHelper.AddNodeToStorage(datanode);
  renderingHelper.Render();

  //### Usage of CompareRenderWindowAgainstReference: See docu of mitkRrenderingTestHelper
  MITK_TEST_CONDITION( renderingHelper.CompareRenderWindowAgainstReference(argc, argv,200.0) == true, "CompareRenderWindowAgainstReference test result positive?" );

  //use this to generate a reference screenshot or save the file:
  bool generateReferenceScreenshot = false;
  if(generateReferenceScreenshot)
  {
    renderingHelper.SaveReferenceScreenShot("/home/christoph/Pictures/RenderingTestData/mitkLabelOverlay3DRendering2DTest.png");
  }

  MITK_TEST_END();
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xmltext.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-17 16:10:35 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLIMP_HXX
#include "xmlimp.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::text;

// ---------------------------------------------------------------------

class SwXMLBodyContext_Impl : public SvXMLImportContext
{
    SwXMLImport& GetSwImport() { return (SwXMLImport&)GetImport(); }

public:

    SwXMLBodyContext_Impl( SwXMLImport& rImport, sal_uInt16 nPrfx,
                             const OUString& rLName );
    virtual ~SwXMLBodyContext_Impl();

    virtual SvXMLImportContext *CreateChildContext(
            sal_uInt16 nPrefix, const OUString& rLocalName,
            const Reference< xml::sax::XAttributeList > & xAttrList );

    virtual void EndElement();
};

SwXMLBodyContext_Impl::SwXMLBodyContext_Impl( SwXMLImport& rImport,
                                              sal_uInt16 nPrfx,
                                                   const OUString& rLName ) :
    SvXMLImportContext( rImport, nPrfx, rLName )
{
}

SwXMLBodyContext_Impl::~SwXMLBodyContext_Impl()
{
}

SvXMLImportContext *SwXMLBodyContext_Impl::CreateChildContext(
        sal_uInt16 nPrefix, const OUString& rLocalName,
        const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;

    pContext = GetSwImport().GetTextImport()->CreateTextChildContext(
            GetImport(), nPrefix, rLocalName, xAttrList,
               XML_TEXT_TYPE_BODY );
    if( !pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );

    return pContext;
}

void SwXMLBodyContext_Impl::EndElement()
{
    /* #108146# Code moved to SwXMLOmport::endDocument */
    GetImport().GetTextImport()->SetOutlineStyles();
}

SvXMLImportContext *SwXMLImport::CreateBodyContext(
                                       const OUString& rLocalName )
{
    SvXMLImportContext *pContext = 0;

    if( !IsStylesOnlyMode() )
         pContext = new SwXMLBodyContext_Impl( *this, XML_NAMESPACE_OFFICE,
                                              rLocalName );
    else
        pContext = new SvXMLImportContext( *this, XML_NAMESPACE_OFFICE,
                                           rLocalName );

    return pContext;
}
<commit_msg>INTEGRATION: CWS oasis (1.9.448); FILE MERGED 2004/03/31 14:24:21 mib 1.9.448.1: First steps of OASIS file format<commit_after>/*************************************************************************
 *
 *  $RCSfile: xmltext.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-13 09:09:01 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLIMP_HXX
#include "xmlimp.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::text;

// ---------------------------------------------------------------------

class SwXMLBodyContentContext_Impl : public SvXMLImportContext
{
    SwXMLImport& GetSwImport() { return (SwXMLImport&)GetImport(); }

public:

    SwXMLBodyContentContext_Impl( SwXMLImport& rImport, sal_uInt16 nPrfx,
                             const OUString& rLName );
    virtual ~SwXMLBodyContentContext_Impl();

    virtual SvXMLImportContext *CreateChildContext(
            sal_uInt16 nPrefix, const OUString& rLocalName,
            const Reference< xml::sax::XAttributeList > & xAttrList );

    // The body element's text:global attribute can be ignored, because
    // we must have the correct object shell already.
    virtual void EndElement();
};

SwXMLBodyContentContext_Impl::SwXMLBodyContentContext_Impl( SwXMLImport& rImport,
                                              sal_uInt16 nPrfx,
                                                   const OUString& rLName ) :
    SvXMLImportContext( rImport, nPrfx, rLName )
{
}

SwXMLBodyContentContext_Impl::~SwXMLBodyContentContext_Impl()
{
}

SvXMLImportContext *SwXMLBodyContentContext_Impl::CreateChildContext(
        sal_uInt16 nPrefix, const OUString& rLocalName,
        const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;

    pContext = GetSwImport().GetTextImport()->CreateTextChildContext(
            GetImport(), nPrefix, rLocalName, xAttrList,
               XML_TEXT_TYPE_BODY );
    if( !pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );

    return pContext;
}

void SwXMLBodyContentContext_Impl::EndElement()
{
    /* #108146# Code moved to SwXMLOmport::endDocument */
    GetImport().GetTextImport()->SetOutlineStyles();
}

SvXMLImportContext *SwXMLImport::CreateBodyContentContext(
                                       const OUString& rLocalName )
{
    SvXMLImportContext *pContext = 0;

    if( !IsStylesOnlyMode() )
         pContext = new SwXMLBodyContentContext_Impl( *this, XML_NAMESPACE_OFFICE,
                                              rLocalName );
    else
        pContext = new SvXMLImportContext( *this, XML_NAMESPACE_OFFICE,
                                           rLocalName );

    return pContext;
}
<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010      Siddharth Srivastava <akssps011@gmail.com>
// Copyright 2011      Bernhard Beschow <bbeschow@cs.tu-berlin.de>
//

#include "AdjustNavigation.h"

#include "MarbleWidget.h"
#include "GeoDataCoordinates.h"
#include "PositionTracking.h"
#include "MarbleDebug.h"
#include "MarbleModel.h"
#include "MarbleMath.h"
#include "global.h"

#include <QtGui/QPixmap>
#include <QtGui/QWidget>
#include <QtCore/QRect>
#include <QtCore/QPointF>
#include <QtCore/QTime>
#include <math.h>

namespace Marble {

class AdjustNavigationPrivate
{
public:

    MarbleWidget        *const m_widget;
    const PositionTracking *const m_tracking;
    AdjustNavigation::CenterMode m_recenterMode;
    bool                 m_adjustZoom;
    QTime                m_lastWidgetInteraction;
    bool                 m_selfInteraction;

    /** Constructor */
    AdjustNavigationPrivate( MarbleWidget *widget );

    /**
     * @brief To center on when reaching custom defined border
     * @param position current gps location
     * @param speed optional speed argument
     */
     void moveOnBorderToCenter( const GeoDataCoordinates &position, qreal speed );

    /**
     * For calculating intersection point of projected LineString from
     * current gps location with the map border
     * @param position current gps location
     */
     GeoDataCoordinates findIntersection( qreal currentX, qreal currentY ) const;

    /**
     * @brief Adjust the zoom value of the map
     * @param currentPosition current location of the gps device
     */
     void adjustZoom( const GeoDataCoordinates &currentPosition, qreal speed );

     /**
       * Center the widget on the given position unless recentering is currently inhibited
       */
     void centerOn( const GeoDataCoordinates &position );
};

AdjustNavigationPrivate::AdjustNavigationPrivate( MarbleWidget *widget ) :
        m_widget( widget ),
        m_tracking( widget->model()->positionTracking() ),
        m_recenterMode( AdjustNavigation::DontRecenter ),
        m_adjustZoom( 0 ),
        m_selfInteraction( false )
{
    m_lastWidgetInteraction.start();
}

void AdjustNavigationPrivate::moveOnBorderToCenter( const GeoDataCoordinates &position, qreal )
{
    qreal lon = 0.0;
    qreal lat = 0.0;

    position.geoCoordinates( lon, lat, GeoDataCoordinates::Degree );

    qreal x = 0.0;
    qreal y = 0.0;
    //recenter if initially the gps location is not visible on the screen
    if(!( m_widget->screenCoordinates( lon, lat, x, y ) ) ) {
         centerOn( position );
    }
    qreal centerLon = m_widget->centerLongitude();
    qreal centerLat = m_widget->centerLatitude();

    qreal centerX = 0.0;
    qreal centerY = 0.0;

    m_widget->screenCoordinates( centerLon, centerLat, centerX, centerY );

    const qreal borderRatio = 0.25;
    //defining the default border distance from map center
    int shiftX = qRound( centerX * borderRatio );
    int shiftY = qRound( centerY * borderRatio );

    QRect recenterBorderBound;
    recenterBorderBound.setCoords( centerX-shiftX, centerY-shiftY, centerX+shiftX,  centerY+shiftY );

    if( !recenterBorderBound.contains( x,y ) ) {
        centerOn( position );
    }
}

GeoDataCoordinates AdjustNavigationPrivate::findIntersection( qreal currentX, qreal currentY ) const
{
    qreal direction = m_tracking->direction();
    if ( direction >= 360 ) {
        direction = fmod( direction,360.0 );
    }

    const qreal width = m_widget->width();
    const qreal height = m_widget->height();

    QPointF intercept;
    QPointF destinationHorizontal;
    QPointF destinationVertical;
    QPointF destination;

    bool crossHorizontal =  false;
    bool crossVertical = false;

    //calculation of intersection point
    if( 0 < direction && direction < 90 ) {
        const qreal angle = direction;

        //Intersection with line x = width
        intercept.setX( width - currentX );
        intercept.setY( intercept.x() / tan( angle ) );
        destinationVertical.setX( width );
        destinationVertical.setY( currentY-intercept.y() );

        //Intersection with line y = 0
        intercept.setY( currentY );
        intercept.setX( intercept.y() * tan( angle ) );
        destinationHorizontal.setX( currentX + intercept.x() );
        destinationHorizontal.setY( 0 );

        if ( destinationVertical.y() < 0 ) {
            crossHorizontal = true;
        }
        else if( destinationHorizontal.x() > width ) {
            crossVertical = true;
        }

    }
    else if( 270 < direction && direction < 360 ) {
        const qreal angle = direction - 270;

        //Intersection with line y = 0
        intercept.setY( currentY );
        intercept.setX( intercept.y() / tan( angle ) );
        destinationHorizontal.setX( currentX - intercept.x() );
        destinationHorizontal.setY( 0 );

        //Intersection with line x = 0
        intercept.setX( currentX );
        intercept.setY( intercept.x() * tan( angle ) );
        destinationVertical.setY( currentY - intercept.y() );
        destinationVertical.setX( 0 );

        if( destinationHorizontal.x() > width ) {
            crossVertical = true;
        }
        else if( destinationVertical.y() < 0 ) {
            crossHorizontal = true;
        }

    }
    else if( 180 < direction && direction < 270  ) {
        const qreal angle = direction - 180;

        //Intersection with line x = 0
        intercept.setX( currentX );
        intercept.setY( intercept.x() / tan( angle ) );
        destinationVertical.setY( currentY + intercept.y() );
        destinationVertical.setX( 0 );

        //Intersection with line y = height
        intercept.setY( currentY );
        intercept.setX( intercept.y() * tan( angle ) );
        destinationHorizontal.setX( currentX - intercept.x() );
        destinationHorizontal.setY( height );

        if ( destinationVertical.y() > height ) {
            crossHorizontal = true;
        }
        else if ( destinationHorizontal.x() < 0 ) {
            crossVertical = true;
        }

    }
    else if( 90 < direction && direction < 180  ) {
        const qreal angle = direction - 90;

        //Intersection with line y = height
        intercept.setY( height - currentY );
        intercept.setX( intercept.y() / tan( angle ) );
        destinationHorizontal.setX( currentX + intercept.x() );
        destinationHorizontal.setY( height );

        //Intersection with line x = width
        intercept.setX( width - currentX );
        intercept.setY( intercept.x() * tan( angle ) );
        destinationVertical.setX( width );
        destinationVertical.setY( currentY + intercept.y() );

        if ( destinationHorizontal.x() > width ) {
            crossVertical = true;
        }
        else if( destinationVertical.y() > height ) {
            crossHorizontal = true;
        }

    }
    else if( direction == 0 ) {
        destinationHorizontal.setX( currentX );
        destinationHorizontal.setY( 0 );
        crossHorizontal = true;
    }
    else if( direction == 90 ) {
        destinationVertical.setX( width );
        destinationVertical.setY( currentY );
        crossVertical = true;
    }
    else if( direction == 190 ) {
        destinationHorizontal.setX( currentX );
        destinationHorizontal.setY( height );
        crossHorizontal = true;
    }
    else if( direction == 270 ) {
        destinationVertical.setX( 0 );
        destinationVertical.setY( currentY );
        crossVertical = true;
    }

    if ( crossHorizontal == true && crossVertical == false ) {
        destination.setX( destinationHorizontal.x() );
        destination.setY( destinationHorizontal.y() );
    }
    else if ( crossVertical == true && crossHorizontal == false ) {
        destination.setX( destinationVertical.x() );
        destination.setY( destinationVertical.y() );
    }

    qreal destinationLon = 0.0;
    qreal destinationLat = 0.0;
    m_widget->geoCoordinates( destination.x(), destination.y(), destinationLon, destinationLat,
                              GeoDataCoordinates::Radian );
    GeoDataCoordinates destinationCoord( destinationLon, destinationLat, GeoDataCoordinates::Radian );

    return destinationCoord;
}

void AdjustNavigationPrivate::adjustZoom( const GeoDataCoordinates &currentPosition, qreal speed )
{
    const qreal lon = currentPosition.longitude( GeoDataCoordinates::Degree );
    const qreal lat = currentPosition.latitude( GeoDataCoordinates::Degree );

    qreal currentX = 0;
    qreal currentY = 0;

    if( !m_widget->screenCoordinates( lon, lat, currentX, currentY ) ) {
        return;
    }

    const GeoDataCoordinates destination = findIntersection( currentX, currentY );

    qreal greatCircleDistance = distanceSphere( currentPosition, destination );
    qreal radius = m_widget->model()->planetRadius();
    qreal distance = greatCircleDistance *  radius;

    if( speed != 0 ) {
        //time(in minutes) remaining to reach the border of the map
        qreal  remainingTime = ( distance / speed ) * SEC2MIN;

        //tolerance time limits( in minutes ) before auto zooming
        qreal thresholdLow = 1.0;
        qreal thresholdHigh = 12.0 * thresholdLow;

        m_selfInteraction = true;
        if ( remainingTime < thresholdLow ) {
            m_widget->zoomOut();
        }
        else if ( remainingTime < thresholdHigh ) {
            /* zoom level optimal, nothing to do */
        }
        else {
            m_widget->zoomIn();
        }
        m_selfInteraction = false;
    }
}

void AdjustNavigationPrivate::centerOn( const GeoDataCoordinates &position )
{
    m_selfInteraction = true;
    m_widget->centerOn( position, false );
    m_selfInteraction = false;
}

AdjustNavigation::AdjustNavigation( MarbleWidget *widget, QObject *parent )
    :QObject( parent ), d( new AdjustNavigationPrivate( widget ) )
{
    connect( widget, SIGNAL( visibleLatLonAltBoxChanged( GeoDataLatLonAltBox ) ),
             this, SLOT( inhibitAutoAdjustments() ) );

    connect( d->m_tracking, SIGNAL( gpsLocation( GeoDataCoordinates, qreal ) ),
                this, SLOT( adjust( GeoDataCoordinates, qreal ) ) );
}

AdjustNavigation::~AdjustNavigation()
{
    delete d;
}

void AdjustNavigation::adjust( const GeoDataCoordinates &position, qreal speed )
{
    if ( d->m_lastWidgetInteraction.elapsed() <= 10 * 1000 ) {
        return;
    }

    switch( d->m_recenterMode ) {
    case DontRecenter:
        /* nothing to do */
        break;
    case AlwaysRecenter:
        d->centerOn( position );
        break;
    case RecenterOnBorder:
        d->moveOnBorderToCenter( position, speed );
        break;
    }

    if ( d->m_adjustZoom ) {
        switch( d->m_recenterMode ) {
        case DontRecenter:
            /* nothing to do */
            break;
        case AlwaysRecenter:
        case RecenterOnBorder: // fallthrough
            d->adjustZoom( position, speed );
            break;
        }
    }
}

void AdjustNavigation::setAutoZoom( bool autoZoom )
{
    d->m_adjustZoom = autoZoom;
    emit autoZoomToggled( autoZoom );
}

void AdjustNavigation::setRecenter( CenterMode recenterMode )
{
    d->m_recenterMode = recenterMode;
    emit recenterModeChanged( recenterMode );
}

void AdjustNavigation::inhibitAutoAdjustments()
{
    if ( !d->m_selfInteraction ) {
        d->m_lastWidgetInteraction.restart();
    }
}

AdjustNavigation::CenterMode AdjustNavigation::recenterMode() const
{
    return d->m_recenterMode;
}

bool AdjustNavigation::autoZoom() const
{
    return d->m_adjustZoom;
}

} // namespace Marble

#include "AdjustNavigation.moc"
<commit_msg>AdjustNavigation: zoom instantly since animated zooming triggers 10 second waiting<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010      Siddharth Srivastava <akssps011@gmail.com>
// Copyright 2011      Bernhard Beschow <bbeschow@cs.tu-berlin.de>
//

#include "AdjustNavigation.h"

#include "MarbleWidget.h"
#include "GeoDataCoordinates.h"
#include "PositionTracking.h"
#include "MarbleDebug.h"
#include "MarbleModel.h"
#include "MarbleMath.h"
#include "global.h"

#include <QtGui/QPixmap>
#include <QtGui/QWidget>
#include <QtCore/QRect>
#include <QtCore/QPointF>
#include <QtCore/QTime>
#include <math.h>

namespace Marble {

class AdjustNavigationPrivate
{
public:

    MarbleWidget        *const m_widget;
    const PositionTracking *const m_tracking;
    AdjustNavigation::CenterMode m_recenterMode;
    bool                 m_adjustZoom;
    QTime                m_lastWidgetInteraction;
    bool                 m_selfInteraction;

    /** Constructor */
    AdjustNavigationPrivate( MarbleWidget *widget );

    /**
     * @brief To center on when reaching custom defined border
     * @param position current gps location
     * @param speed optional speed argument
     */
     void moveOnBorderToCenter( const GeoDataCoordinates &position, qreal speed );

    /**
     * For calculating intersection point of projected LineString from
     * current gps location with the map border
     * @param position current gps location
     */
     GeoDataCoordinates findIntersection( qreal currentX, qreal currentY ) const;

    /**
     * @brief Adjust the zoom value of the map
     * @param currentPosition current location of the gps device
     */
     void adjustZoom( const GeoDataCoordinates &currentPosition, qreal speed );

     /**
       * Center the widget on the given position unless recentering is currently inhibited
       */
     void centerOn( const GeoDataCoordinates &position );
};

AdjustNavigationPrivate::AdjustNavigationPrivate( MarbleWidget *widget ) :
        m_widget( widget ),
        m_tracking( widget->model()->positionTracking() ),
        m_recenterMode( AdjustNavigation::DontRecenter ),
        m_adjustZoom( 0 ),
        m_selfInteraction( false )
{
    m_lastWidgetInteraction.start();
}

void AdjustNavigationPrivate::moveOnBorderToCenter( const GeoDataCoordinates &position, qreal )
{
    qreal lon = 0.0;
    qreal lat = 0.0;

    position.geoCoordinates( lon, lat, GeoDataCoordinates::Degree );

    qreal x = 0.0;
    qreal y = 0.0;
    //recenter if initially the gps location is not visible on the screen
    if(!( m_widget->screenCoordinates( lon, lat, x, y ) ) ) {
         centerOn( position );
    }
    qreal centerLon = m_widget->centerLongitude();
    qreal centerLat = m_widget->centerLatitude();

    qreal centerX = 0.0;
    qreal centerY = 0.0;

    m_widget->screenCoordinates( centerLon, centerLat, centerX, centerY );

    const qreal borderRatio = 0.25;
    //defining the default border distance from map center
    int shiftX = qRound( centerX * borderRatio );
    int shiftY = qRound( centerY * borderRatio );

    QRect recenterBorderBound;
    recenterBorderBound.setCoords( centerX-shiftX, centerY-shiftY, centerX+shiftX,  centerY+shiftY );

    if( !recenterBorderBound.contains( x,y ) ) {
        centerOn( position );
    }
}

GeoDataCoordinates AdjustNavigationPrivate::findIntersection( qreal currentX, qreal currentY ) const
{
    qreal direction = m_tracking->direction();
    if ( direction >= 360 ) {
        direction = fmod( direction,360.0 );
    }

    const qreal width = m_widget->width();
    const qreal height = m_widget->height();

    QPointF intercept;
    QPointF destinationHorizontal;
    QPointF destinationVertical;
    QPointF destination;

    bool crossHorizontal =  false;
    bool crossVertical = false;

    //calculation of intersection point
    if( 0 < direction && direction < 90 ) {
        const qreal angle = direction;

        //Intersection with line x = width
        intercept.setX( width - currentX );
        intercept.setY( intercept.x() / tan( angle ) );
        destinationVertical.setX( width );
        destinationVertical.setY( currentY-intercept.y() );

        //Intersection with line y = 0
        intercept.setY( currentY );
        intercept.setX( intercept.y() * tan( angle ) );
        destinationHorizontal.setX( currentX + intercept.x() );
        destinationHorizontal.setY( 0 );

        if ( destinationVertical.y() < 0 ) {
            crossHorizontal = true;
        }
        else if( destinationHorizontal.x() > width ) {
            crossVertical = true;
        }

    }
    else if( 270 < direction && direction < 360 ) {
        const qreal angle = direction - 270;

        //Intersection with line y = 0
        intercept.setY( currentY );
        intercept.setX( intercept.y() / tan( angle ) );
        destinationHorizontal.setX( currentX - intercept.x() );
        destinationHorizontal.setY( 0 );

        //Intersection with line x = 0
        intercept.setX( currentX );
        intercept.setY( intercept.x() * tan( angle ) );
        destinationVertical.setY( currentY - intercept.y() );
        destinationVertical.setX( 0 );

        if( destinationHorizontal.x() > width ) {
            crossVertical = true;
        }
        else if( destinationVertical.y() < 0 ) {
            crossHorizontal = true;
        }

    }
    else if( 180 < direction && direction < 270  ) {
        const qreal angle = direction - 180;

        //Intersection with line x = 0
        intercept.setX( currentX );
        intercept.setY( intercept.x() / tan( angle ) );
        destinationVertical.setY( currentY + intercept.y() );
        destinationVertical.setX( 0 );

        //Intersection with line y = height
        intercept.setY( currentY );
        intercept.setX( intercept.y() * tan( angle ) );
        destinationHorizontal.setX( currentX - intercept.x() );
        destinationHorizontal.setY( height );

        if ( destinationVertical.y() > height ) {
            crossHorizontal = true;
        }
        else if ( destinationHorizontal.x() < 0 ) {
            crossVertical = true;
        }

    }
    else if( 90 < direction && direction < 180  ) {
        const qreal angle = direction - 90;

        //Intersection with line y = height
        intercept.setY( height - currentY );
        intercept.setX( intercept.y() / tan( angle ) );
        destinationHorizontal.setX( currentX + intercept.x() );
        destinationHorizontal.setY( height );

        //Intersection with line x = width
        intercept.setX( width - currentX );
        intercept.setY( intercept.x() * tan( angle ) );
        destinationVertical.setX( width );
        destinationVertical.setY( currentY + intercept.y() );

        if ( destinationHorizontal.x() > width ) {
            crossVertical = true;
        }
        else if( destinationVertical.y() > height ) {
            crossHorizontal = true;
        }

    }
    else if( direction == 0 ) {
        destinationHorizontal.setX( currentX );
        destinationHorizontal.setY( 0 );
        crossHorizontal = true;
    }
    else if( direction == 90 ) {
        destinationVertical.setX( width );
        destinationVertical.setY( currentY );
        crossVertical = true;
    }
    else if( direction == 190 ) {
        destinationHorizontal.setX( currentX );
        destinationHorizontal.setY( height );
        crossHorizontal = true;
    }
    else if( direction == 270 ) {
        destinationVertical.setX( 0 );
        destinationVertical.setY( currentY );
        crossVertical = true;
    }

    if ( crossHorizontal == true && crossVertical == false ) {
        destination.setX( destinationHorizontal.x() );
        destination.setY( destinationHorizontal.y() );
    }
    else if ( crossVertical == true && crossHorizontal == false ) {
        destination.setX( destinationVertical.x() );
        destination.setY( destinationVertical.y() );
    }

    qreal destinationLon = 0.0;
    qreal destinationLat = 0.0;
    m_widget->geoCoordinates( destination.x(), destination.y(), destinationLon, destinationLat,
                              GeoDataCoordinates::Radian );
    GeoDataCoordinates destinationCoord( destinationLon, destinationLat, GeoDataCoordinates::Radian );

    return destinationCoord;
}

void AdjustNavigationPrivate::adjustZoom( const GeoDataCoordinates &currentPosition, qreal speed )
{
    const qreal lon = currentPosition.longitude( GeoDataCoordinates::Degree );
    const qreal lat = currentPosition.latitude( GeoDataCoordinates::Degree );

    qreal currentX = 0;
    qreal currentY = 0;

    if( !m_widget->screenCoordinates( lon, lat, currentX, currentY ) ) {
        return;
    }

    const GeoDataCoordinates destination = findIntersection( currentX, currentY );

    qreal greatCircleDistance = distanceSphere( currentPosition, destination );
    qreal radius = m_widget->model()->planetRadius();
    qreal distance = greatCircleDistance *  radius;

    if( speed != 0 ) {
        //time(in minutes) remaining to reach the border of the map
        qreal  remainingTime = ( distance / speed ) * SEC2MIN;

        //tolerance time limits( in minutes ) before auto zooming
        qreal thresholdLow = 1.0;
        qreal thresholdHigh = 12.0 * thresholdLow;

        m_selfInteraction = true;
        if ( remainingTime < thresholdLow ) {
            m_widget->zoomOut( Instant );
        }
        else if ( remainingTime < thresholdHigh ) {
            /* zoom level optimal, nothing to do */
        }
        else {
            m_widget->zoomIn( Instant );
        }
        m_selfInteraction = false;
    }
}

void AdjustNavigationPrivate::centerOn( const GeoDataCoordinates &position )
{
    m_selfInteraction = true;
    m_widget->centerOn( position, false );
    m_selfInteraction = false;
}

AdjustNavigation::AdjustNavigation( MarbleWidget *widget, QObject *parent )
    :QObject( parent ), d( new AdjustNavigationPrivate( widget ) )
{
    connect( widget, SIGNAL( visibleLatLonAltBoxChanged( GeoDataLatLonAltBox ) ),
             this, SLOT( inhibitAutoAdjustments() ) );

    connect( d->m_tracking, SIGNAL( gpsLocation( GeoDataCoordinates, qreal ) ),
                this, SLOT( adjust( GeoDataCoordinates, qreal ) ) );
}

AdjustNavigation::~AdjustNavigation()
{
    delete d;
}

void AdjustNavigation::adjust( const GeoDataCoordinates &position, qreal speed )
{
    if ( d->m_lastWidgetInteraction.elapsed() <= 10 * 1000 ) {
        return;
    }

    switch( d->m_recenterMode ) {
    case DontRecenter:
        /* nothing to do */
        break;
    case AlwaysRecenter:
        d->centerOn( position );
        break;
    case RecenterOnBorder:
        d->moveOnBorderToCenter( position, speed );
        break;
    }

    if ( d->m_adjustZoom ) {
        switch( d->m_recenterMode ) {
        case DontRecenter:
            /* nothing to do */
            break;
        case AlwaysRecenter:
        case RecenterOnBorder: // fallthrough
            d->adjustZoom( position, speed );
            break;
        }
    }
}

void AdjustNavigation::setAutoZoom( bool autoZoom )
{
    d->m_adjustZoom = autoZoom;
    emit autoZoomToggled( autoZoom );
}

void AdjustNavigation::setRecenter( CenterMode recenterMode )
{
    d->m_recenterMode = recenterMode;
    emit recenterModeChanged( recenterMode );
}

void AdjustNavigation::inhibitAutoAdjustments()
{
    if ( !d->m_selfInteraction ) {
        d->m_lastWidgetInteraction.restart();
    }
}

AdjustNavigation::CenterMode AdjustNavigation::recenterMode() const
{
    return d->m_recenterMode;
}

bool AdjustNavigation::autoZoom() const
{
    return d->m_adjustZoom;
}

} // namespace Marble

#include "AdjustNavigation.moc"
<|endoftext|>