diff --git a/Core/Code/Testing/mitkSliceNavigationControllerTest.cpp b/Core/Code/Testing/mitkSliceNavigationControllerTest.cpp index 2e5f13848b..0b92d64da7 100644 --- a/Core/Code/Testing/mitkSliceNavigationControllerTest.cpp +++ b/Core/Code/Testing/mitkSliceNavigationControllerTest.cpp @@ -1,586 +1,586 @@ /*=================================================================== 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. ===================================================================*/ #include "mitkSliceNavigationController.h" #include "mitkPlaneGeometry.h" #include "mitkSlicedGeometry3D.h" #include "mitkTimeSlicedGeometry.h" #include "mitkRotationOperation.h" #include "mitkInteractionConst.h" #include "mitkPlanePositionManager.h" #include "mitkTestingMacros.h" #include "usGetModuleContext.h" #include "usModuleContext.h" #include "usServiceReference.h" #include #include #include bool operator==(const mitk::Geometry3D & left, const mitk::Geometry3D & right) { mitk::BoundingBox::BoundsArrayType leftbounds, rightbounds; leftbounds =left.GetBounds(); rightbounds=right.GetBounds(); unsigned int i; for(i=0;i<6;++i) if(mitk::Equal(leftbounds[i],rightbounds[i])==false) return false; const mitk::Geometry3D::TransformType::MatrixType & leftmatrix = left.GetIndexToWorldTransform()->GetMatrix(); const mitk::Geometry3D::TransformType::MatrixType & rightmatrix = right.GetIndexToWorldTransform()->GetMatrix(); unsigned int j; for(i=0;i<3;++i) { const mitk::Geometry3D::TransformType::MatrixType::ValueType* leftvector = leftmatrix[i]; const mitk::Geometry3D::TransformType::MatrixType::ValueType* rightvector = rightmatrix[i]; for(j=0;j<3;++j) if(mitk::Equal(leftvector[i],rightvector[i])==false) return false; } const mitk::Geometry3D::TransformType::OffsetType & leftoffset = left.GetIndexToWorldTransform()->GetOffset(); const mitk::Geometry3D::TransformType::OffsetType & rightoffset = right.GetIndexToWorldTransform()->GetOffset(); for(i=0;i<3;++i) if(mitk::Equal(leftoffset[i],rightoffset[i])==false) return false; return true; } int compareGeometry(const mitk::Geometry3D & geometry, const mitk::ScalarType& width, const mitk::ScalarType& height, const mitk::ScalarType& numSlices, const mitk::ScalarType& widthInMM, const mitk::ScalarType& heightInMM, const mitk::ScalarType& thicknessInMM, const mitk::Point3D& cornerpoint0, const mitk::Vector3D& right, const mitk::Vector3D& bottom, const mitk::Vector3D& normal) { std::cout << "Testing width, height and thickness (in units): "; if((mitk::Equal(geometry.GetExtent(0),width)==false) || (mitk::Equal(geometry.GetExtent(1),height)==false) || (mitk::Equal(geometry.GetExtent(2),numSlices)==false) ) { std::cout<<"[FAILED]"<GetCornerPoint(0), cornerpoint0)==false) { std::cout<<"[FAILED]"<SetInputWorldGeometry(geometry); std::cout<<"[PASSED]"<SetViewDirection(mitk::SliceNavigationController::Axial); std::cout<<"[PASSED]"<Update(); std::cout<<"[PASSED]"<GetCreatedWorldGeometry(), width, height, numSlices, widthInMM, heightInMM, thicknessInMM*numSlices, axialcornerpoint0, right, bottom*(-1.0), normal*(-1.0)); if(result!=EXIT_SUCCESS) { std::cout<<"[FAILED]"<SetViewDirection(mitk::SliceNavigationController::Frontal); std::cout<<"[PASSED]"<Update(); std::cout<<"[PASSED]"<GetAxisVector(1)*(+0.5/geometry->GetExtent(1)); result = compareGeometry(*sliceCtrl->GetCreatedWorldGeometry(), width, numSlices, height, widthInMM, thicknessInMM*numSlices, heightInMM, frontalcornerpoint0, right, normal, bottom); if(result!=EXIT_SUCCESS) { std::cout<<"[FAILED]"<SetViewDirection(mitk::SliceNavigationController::Sagittal); std::cout<<"[PASSED]"<Update(); std::cout<<"[PASSED]"<GetAxisVector(0)*(+0.5/geometry->GetExtent(0)); result = compareGeometry(*sliceCtrl->GetCreatedWorldGeometry(), height, numSlices, width, heightInMM, thicknessInMM*numSlices, widthInMM, sagittalcornerpoint0, bottom, normal, right); if(result!=EXIT_SUCCESS) { std::cout<<"[FAILED]"<InitializeStandardPlane(right.GetVnlVector(), bottom.GetVnlVector(), &spacing); planegeometry->SetOrigin(origin); //Create SlicedGeometry3D out of planeGeometry mitk::SlicedGeometry3D::Pointer slicedgeometry1 = mitk::SlicedGeometry3D::New(); unsigned int numSlices = 20; slicedgeometry1->InitializeEvenlySpaced(planegeometry, thicknessInMM, numSlices, false); //Create another slicedgeo which will be rotated mitk::SlicedGeometry3D::Pointer slicedgeometry2 = mitk::SlicedGeometry3D::New(); slicedgeometry2->InitializeEvenlySpaced(planegeometry, thicknessInMM, numSlices, false); //Create geo3D as reference mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); geometry->SetBounds(slicedgeometry1->GetBounds()); geometry->SetIndexToWorldTransform(slicedgeometry1->GetIndexToWorldTransform()); //Initialize planes for (int i=0; i < (int)numSlices; i++) { mitk::PlaneGeometry::Pointer geo2d = mitk::PlaneGeometry::New(); geo2d->Initialize(); geo2d->SetReferenceGeometry(geometry); slicedgeometry1->SetGeometry2D(geo2d,i); } for (int i=0; i < (int)numSlices; i++) { mitk::PlaneGeometry::Pointer geo2d = mitk::PlaneGeometry::New(); geo2d->Initialize(); geo2d->SetReferenceGeometry(geometry); slicedgeometry2->SetGeometry2D(geo2d,i); } slicedgeometry1->SetReferenceGeometry(geometry); slicedgeometry2->SetReferenceGeometry(geometry); //Create SNC mitk::SliceNavigationController::Pointer sliceCtrl1 = mitk::SliceNavigationController::New(); sliceCtrl1->SetInputWorldGeometry(slicedgeometry1); sliceCtrl1->Update(); mitk::SliceNavigationController::Pointer sliceCtrl2 = mitk::SliceNavigationController::New(); sliceCtrl2->SetInputWorldGeometry(slicedgeometry2); sliceCtrl2->Update(); slicedgeometry1->SetSliceNavigationController(sliceCtrl1); slicedgeometry2->SetSliceNavigationController(sliceCtrl2); // Whats current geometry? MITK_INFO << "center: " << sliceCtrl1->GetCurrentPlaneGeometry()->GetCenter(); MITK_INFO << "normal: " << sliceCtrl1->GetCurrentPlaneGeometry()->GetNormal(); MITK_INFO << "origin: " << sliceCtrl1->GetCurrentPlaneGeometry()->GetOrigin(); MITK_INFO << "axis0 : " << sliceCtrl1->GetCurrentPlaneGeometry()->GetAxisVector(0); MITK_INFO << "aixs1 : " << sliceCtrl1->GetCurrentPlaneGeometry()->GetAxisVector(1); // // Now reorient slices (ONE POINT, ONE NORMAL) mitk::Point3D oldCenter, oldOrigin; mitk::Vector3D oldAxis0, oldAxis1; oldCenter = sliceCtrl1->GetCurrentPlaneGeometry()->GetCenter(); oldOrigin = sliceCtrl1->GetCurrentPlaneGeometry()->GetOrigin(); oldAxis0 = sliceCtrl1->GetCurrentPlaneGeometry()->GetAxisVector(0); oldAxis1 = sliceCtrl1->GetCurrentPlaneGeometry()->GetAxisVector(1); mitk::Point3D orientCenter; mitk::Vector3D orientNormal; orientCenter = oldCenter; mitk::FillVector3D(orientNormal, 0.3, 0.1, 0.8); orientNormal.Normalize(); sliceCtrl1->ReorientSlices(orientCenter,orientNormal); mitk::Point3D newCenter, newOrigin; mitk::Vector3D newNormal; newCenter = sliceCtrl1->GetCurrentPlaneGeometry()->GetCenter(); newOrigin = sliceCtrl1->GetCurrentPlaneGeometry()->GetOrigin(); newNormal = sliceCtrl1->GetCurrentPlaneGeometry()->GetNormal(); newNormal.Normalize(); itk::Index<3> orientCenterIdx; itk::Index<3> newCenterIdx; sliceCtrl1->GetCurrentGeometry3D()->WorldToIndex(orientCenter, orientCenterIdx); sliceCtrl1->GetCurrentGeometry3D()->WorldToIndex(newCenter, newCenterIdx); if ( (newCenterIdx != orientCenterIdx) || ( !mitk::Equal(orientNormal, newNormal) ) ) { MITK_INFO << "Reorient Planes (1 point, 1 vector) not working as it should"; MITK_INFO << "orientCenterIdx: " << orientCenterIdx; MITK_INFO << "newCenterIdx: " << newCenterIdx; MITK_INFO << "orientNormal: " << orientNormal; MITK_INFO << "newNormal: " << newNormal; return EXIT_FAILURE; } // // Now reorient slices (center, vec0, vec1 ) mitk::Vector3D orientAxis0, orientAxis1, newAxis0, newAxis1; mitk::FillVector3D(orientAxis0, 1.0, 0.0, 0.0); mitk::FillVector3D(orientAxis1, 0.0, 1.0, 0.0); orientAxis0.Normalize(); orientAxis1.Normalize(); sliceCtrl1->ReorientSlices(orientCenter,orientAxis0, orientAxis1); newAxis0 = sliceCtrl1->GetCurrentPlaneGeometry()->GetAxisVector(0); newAxis1 = sliceCtrl1->GetCurrentPlaneGeometry()->GetAxisVector(1); newCenter = sliceCtrl1->GetCurrentPlaneGeometry()->GetCenter(); newAxis0.Normalize(); newAxis1.Normalize(); sliceCtrl1->GetCurrentGeometry3D()->WorldToIndex(orientCenter, orientCenterIdx); sliceCtrl1->GetCurrentGeometry3D()->WorldToIndex(newCenter, newCenterIdx); if ( (newCenterIdx != orientCenterIdx) || - ( !mitk::Equal(orientAxis0, newAxis0) ) || - ( !mitk::Equal(orientAxis1, newAxis1) ) + ( !mitk::Equal(orientAxis0, newAxis0, 1E-12) ) || + ( !mitk::Equal(orientAxis1, newAxis1, 1E-12 )) ) { MITK_INFO << "Reorient Planes (point, vec, vec) not working as it should"; MITK_INFO << "orientCenterIdx: " << orientCenterIdx; MITK_INFO << "newCenterIdx: " << newCenterIdx; MITK_INFO << "orientAxis0: " << orientAxis0; MITK_INFO << "newAxis0: " << newAxis0; MITK_INFO << "orientAxis1: " << orientAxis1; MITK_INFO << "newAxis1: " << newAxis1; return EXIT_FAILURE; } return EXIT_SUCCESS; } int testRestorePlanePostionOperation () { //Create PlaneGeometry mitk::PlaneGeometry::Pointer planegeometry = mitk::PlaneGeometry::New(); mitk::Point3D origin; mitk::Vector3D right, bottom, normal; mitk::ScalarType width, height; mitk::ScalarType widthInMM, heightInMM, thicknessInMM; width = 100; widthInMM = width; height = 200; heightInMM = height; thicknessInMM = 1.5; mitk::FillVector3D(origin, 4.5, 7.3, 11.2); mitk::FillVector3D(right, widthInMM, 0, 0); mitk::FillVector3D(bottom, 0, heightInMM, 0); mitk::FillVector3D(normal, 0, 0, thicknessInMM); mitk::Vector3D spacing; normal.Normalize(); normal *= thicknessInMM; mitk::FillVector3D(spacing, 1.0, 1.0, thicknessInMM); planegeometry->InitializeStandardPlane(right.GetVnlVector(), bottom.GetVnlVector(), &spacing); planegeometry->SetOrigin(origin); //Create SlicedGeometry3D out of planeGeometry mitk::SlicedGeometry3D::Pointer slicedgeometry1 = mitk::SlicedGeometry3D::New(); unsigned int numSlices = 300; slicedgeometry1->InitializeEvenlySpaced(planegeometry, thicknessInMM, numSlices, false); //Create another slicedgeo which will be rotated mitk::SlicedGeometry3D::Pointer slicedgeometry2 = mitk::SlicedGeometry3D::New(); slicedgeometry2->InitializeEvenlySpaced(planegeometry, thicknessInMM, numSlices, false); //Create geo3D as reference mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); geometry->SetBounds(slicedgeometry1->GetBounds()); geometry->SetIndexToWorldTransform(slicedgeometry1->GetIndexToWorldTransform()); //Initialize planes for (int i=0; i < (int)numSlices; i++) { mitk::PlaneGeometry::Pointer geo2d = mitk::PlaneGeometry::New(); geo2d->Initialize(); geo2d->SetReferenceGeometry(geometry); slicedgeometry1->SetGeometry2D(geo2d,i); } for (int i=0; i < (int)numSlices; i++) { mitk::PlaneGeometry::Pointer geo2d = mitk::PlaneGeometry::New(); geo2d->Initialize(); geo2d->SetReferenceGeometry(geometry); slicedgeometry2->SetGeometry2D(geo2d,i); } slicedgeometry1->SetReferenceGeometry(geometry); slicedgeometry2->SetReferenceGeometry(geometry); //Create SNC mitk::SliceNavigationController::Pointer sliceCtrl1 = mitk::SliceNavigationController::New(); sliceCtrl1->SetInputWorldGeometry(slicedgeometry1); sliceCtrl1->Update(); mitk::SliceNavigationController::Pointer sliceCtrl2 = mitk::SliceNavigationController::New(); sliceCtrl2->SetInputWorldGeometry(slicedgeometry2); sliceCtrl2->Update(); slicedgeometry1->SetSliceNavigationController(sliceCtrl1); slicedgeometry2->SetSliceNavigationController(sliceCtrl2); //Rotate slicedgeo2 double angle = 63.84; mitk::Vector3D rotationVector; mitk::FillVector3D( rotationVector, 0.5, 0.95, 0.23 ); mitk::Point3D center = slicedgeometry2->GetCenter(); mitk::RotationOperation* op = new mitk::RotationOperation( mitk::OpROTATE, center, rotationVector, angle ); slicedgeometry2->ExecuteOperation(op); sliceCtrl2->Update(); us::ServiceReference serviceRef = us::GetModuleContext()->GetServiceReference(); mitk::PlanePositionManagerService* service = us::GetModuleContext()->GetService(serviceRef); service->AddNewPlanePosition(slicedgeometry2->GetGeometry2D(0), 178); sliceCtrl1->ExecuteOperation(service->GetPlanePosition(0)); sliceCtrl1->Update(); mitk::Geometry2D* planeRotated = slicedgeometry2->GetGeometry2D(178); mitk::Geometry2D* planeRestored = dynamic_cast< const mitk::SlicedGeometry3D*>(sliceCtrl1->GetCurrentGeometry3D())->GetGeometry2D(178); try{ MITK_TEST_CONDITION_REQUIRED(mitk::MatrixEqualElementWise(planeRotated->GetIndexToWorldTransform()->GetMatrix(), planeRestored->GetIndexToWorldTransform()->GetMatrix()),"Testing for IndexToWorld"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(planeRotated->GetOrigin(), planeRestored->GetOrigin(),2*mitk::eps),"Testing for origin"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(planeRotated->GetSpacing(), planeRestored->GetSpacing()),"Testing for spacing"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(slicedgeometry2->GetDirectionVector(), dynamic_cast< const mitk::SlicedGeometry3D*>(sliceCtrl1->GetCurrentGeometry3D())->GetDirectionVector()),"Testing for directionvector"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(slicedgeometry2->GetSlices(), dynamic_cast< const mitk::SlicedGeometry3D*>(sliceCtrl1->GetCurrentGeometry3D())->GetSlices()),"Testing for numslices"); MITK_TEST_CONDITION_REQUIRED(mitk::MatrixEqualElementWise(slicedgeometry2->GetIndexToWorldTransform()->GetMatrix(), dynamic_cast< const mitk::SlicedGeometry3D*>(sliceCtrl1->GetCurrentGeometry3D())->GetIndexToWorldTransform()->GetMatrix()),"Testing for IndexToWorld"); } catch(...) { return EXIT_FAILURE; } return EXIT_SUCCESS; } int mitkSliceNavigationControllerTest(int /*argc*/, char* /*argv*/[]) { int result=EXIT_FAILURE; std::cout << "Creating and initializing a PlaneGeometry: "; mitk::PlaneGeometry::Pointer planegeometry = mitk::PlaneGeometry::New(); mitk::Point3D origin; mitk::Vector3D right, bottom, normal; mitk::ScalarType width, height; mitk::ScalarType widthInMM, heightInMM, thicknessInMM; width = 100; widthInMM = width; height = 200; heightInMM = height; thicknessInMM = 1.5; // mitk::FillVector3D(origin, 0, 0, thicknessInMM*0.5); mitk::FillVector3D(origin, 4.5, 7.3, 11.2); mitk::FillVector3D(right, widthInMM, 0, 0); mitk::FillVector3D(bottom, 0, heightInMM, 0); mitk::FillVector3D(normal, 0, 0, thicknessInMM); mitk::Vector3D spacing; normal.Normalize(); normal *= thicknessInMM; mitk::FillVector3D(spacing, 1.0, 1.0, thicknessInMM); planegeometry->InitializeStandardPlane(right.GetVnlVector(), bottom.GetVnlVector(), &spacing); planegeometry->SetOrigin(origin); std::cout<<"[PASSED]"<InitializeEvenlySpaced(planegeometry, thicknessInMM, numSlices, false); std::cout<<"[PASSED]"<SetBounds(slicedgeometry->GetBounds()); geometry->SetIndexToWorldTransform(slicedgeometry->GetIndexToWorldTransform()); std::cout<<"[PASSED]"<GetCornerPoint(0); result=testGeometry(geometry, width, height, numSlices, widthInMM, heightInMM, thicknessInMM, cornerpoint0, right, bottom, normal); if(result!=EXIT_SUCCESS) return result; mitk::AffineTransform3D::Pointer transform = mitk::AffineTransform3D::New(); transform->SetMatrix(geometry->GetIndexToWorldTransform()->GetMatrix()); mitk::BoundingBox::Pointer boundingbox = geometry->CalculateBoundingBoxRelativeToTransform(transform); geometry->SetBounds(boundingbox->GetBounds()); cornerpoint0 = geometry->GetCornerPoint(0); result=testGeometry(geometry, width, height, numSlices, widthInMM, heightInMM, thicknessInMM, cornerpoint0, right, bottom, normal); if(result!=EXIT_SUCCESS) return result; std::cout << "Changing the IndexToWorldTransform of the geometry to a rotated version by SetIndexToWorldTransform() (keep cornerpoint0): "; transform = mitk::AffineTransform3D::New(); mitk::AffineTransform3D::MatrixType::InternalMatrixType vnlmatrix; vnlmatrix = planegeometry->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix(); mitk::VnlVector axis(3); mitk::FillVector3D(axis, 1.0, 1.0, 1.0); axis.normalize(); vnl_quaternion rotation(axis, 0.223); vnlmatrix = rotation.rotation_matrix_transpose()*vnlmatrix; mitk::Matrix3D matrix; matrix = vnlmatrix; transform->SetMatrix(matrix); transform->SetOffset(cornerpoint0.GetVectorFromOrigin()); right.SetVnlVector( rotation.rotation_matrix_transpose()*right.GetVnlVector() ); bottom.SetVnlVector(rotation.rotation_matrix_transpose()*bottom.GetVnlVector()); normal.SetVnlVector(rotation.rotation_matrix_transpose()*normal.GetVnlVector()); geometry->SetIndexToWorldTransform(transform); std::cout<<"[PASSED]"<GetCornerPoint(0); result = testGeometry(geometry, width, height, numSlices, widthInMM, heightInMM, thicknessInMM, cornerpoint0, right, bottom, normal); if(result!=EXIT_SUCCESS) return result; //Testing Execute RestorePlanePositionOperation result = testRestorePlanePostionOperation(); if(result!=EXIT_SUCCESS) return result; //Testing ReorientPlanes result = testReorientPlanes(); if(result!=EXIT_SUCCESS) return result; std::cout<<"[TEST DONE]"< #include #include #include #include mitk::InterpolateLinesFilter::InterpolateLinesFilter() : m_SplineResolution(10), m_GeometryForInterpolation(NULL), m_Length(0.0) { m_SpX=vtkCardinalSpline::New(); m_SpY=vtkCardinalSpline::New(); m_SpZ=vtkCardinalSpline::New(); } mitk::InterpolateLinesFilter::~InterpolateLinesFilter() { m_SpX->Delete(); m_SpY->Delete(); m_SpZ->Delete(); } void mitk::InterpolateLinesFilter::GenerateOutputInformation() { mitk::Mesh::ConstPointer input = this->GetInput(); mitk::Surface::Pointer output = this->GetOutput(0); itkDebugMacro(<<"GenerateOutputInformation()"); if(input.IsNull()) return; if(m_GeometryForInterpolation.IsNotNull()) output->SetGeometry(static_cast(m_GeometryForInterpolation->Clone().GetPointer())); else output->SetGeometry(static_cast(input->GetGeometry()->Clone().GetPointer())); } void mitk::InterpolateLinesFilter::GenerateData() { mitk::Mesh::ConstPointer input = this->GetInput(); mitk::Surface::Pointer output = this->GetOutput(0); vtkPolyData *polyData = vtkPolyData::New(); vtkPoints *points = vtkPoints::New(); vtkCellArray *cellarray = vtkCellArray::New(); mitk::Mesh::PointType thisPoint; m_Length = 0.0; //iterate through all cells and build tubes Mesh::ConstCellIterator cellIt, cellEnd; cellEnd = input->GetMesh()->GetCells()->End(); for( cellIt = input->GetMesh()->GetCells()->Begin(); cellIt != cellEnd; ++cellIt ) { if(((*cellIt->Value()).GetType()==mitk::Mesh::CellType::POLYGON_CELL) && ((*cellIt->Value()).GetNumberOfPoints()>=2)) BuildPointAndVectorList(*cellIt->Value(), points, cellarray); } polyData->SetPoints( points ); points->Delete(); polyData->SetLines( cellarray ); cellarray->Delete(); output->SetVtkPolyData(polyData); polyData->Delete(); } void mitk::InterpolateLinesFilter::BuildPointAndVectorList(mitk::Mesh::CellType& cell, vtkPoints* points, vtkCellArray* cellarray) { const mitk::Mesh* input = GetInput(); Mesh::PointIdIterator ptIt; Mesh::PointIdIterator ptEnd; ptEnd = cell.PointIdsEnd(); Point3D pt; int i, size=cell.GetNumberOfPoints(); int closed_loop_pre_load=0;//m_SplineResolution; if(m_GeometryForInterpolation.IsNull()) { - //bei geschlossener Kontur: vor dem ersten Punkt die zwei letzten einfügen für glatten Übergang + //when the contour is closed: first point insert behind two last points for smooth crossing ptIt = ptEnd; ptIt-=closed_loop_pre_load+1; for(i=0;iGetPoint(*ptIt); m_SpX->AddPoint(i, pt[0]); m_SpY->AddPoint(i, pt[1]); m_SpZ->AddPoint(i, pt[2]); } - //Punkte einfügen + //insert points for(ptIt = cell.PointIdsBegin();iGetPoint(*ptIt); m_SpX->AddPoint(i, pt[0]); m_SpY->AddPoint(i, pt[1]); m_SpZ->AddPoint(i, pt[2]); } - //bei geschlossener Kontur: nach dem letzten Punkt die zwei ersten einfügen für glatten Übergang + //when the contour is closed: after the last point insert two first points for smooth crossing int j; for(j=0,ptIt = cell.PointIdsBegin();jGetPoint(*ptIt); m_SpX->AddPoint(i, pt[0]); m_SpY->AddPoint(i, pt[1]); m_SpZ->AddPoint(i, pt[2]); } //bool first = true; Point3D lastPt, firstPt; Vector3D vec; float t, step=1.0f/m_SplineResolution; size=(size-1)*m_SplineResolution; i=closed_loop_pre_load; cellarray->InsertNextCell(size); for(t=closed_loop_pre_load;iEvaluate(t), m_SpY->Evaluate(t), m_SpZ->Evaluate(t)); cellarray->InsertCellPoint(points->InsertNextPoint(pt)); } } else //m_GeometryForInterpolation!=NULL { Point2D pt2d; - //bei geschlossener Kontur: vor dem ersten Punkt die zwei letzten einfügen für glatten Übergang + //when the contour is closed: before the first point insert two last points for smooth crossing ptIt = ptEnd; ptIt-=closed_loop_pre_load+1; for(i=0;iMap(input->GetPoint(*ptIt), pt2d); m_SpX->AddPoint(i, pt2d[0]); m_SpY->AddPoint(i, pt2d[1]); } - //Punkte einfügen + //insert points for(ptIt = cell.PointIdsBegin();iMap(input->GetPoint(*ptIt), pt2d); m_SpX->AddPoint(i, pt2d[0]); m_SpY->AddPoint(i, pt2d[1]); } - //bei geschlossener Kontur: nach dem letzten Punkt die zwei ersten einfügen für glatten Übergang + //when the contour is closed: after the last point insert two first points for smooth crossing int j; for(j=0,ptIt = cell.PointIdsBegin();jMap(input->GetPoint(*ptIt), pt2d); m_SpX->AddPoint(i, pt2d[0]); m_SpY->AddPoint(i, pt2d[1]); } bool first = true; Point3D lastPt; lastPt.Fill(0); Vector3D vec; float t, step=1.0f/m_SplineResolution; size=(size-1)*m_SplineResolution; i=closed_loop_pre_load; cellarray->InsertNextCell(size); for(t=closed_loop_pre_load;iEvaluate(t); pt2d[1] = m_SpY->Evaluate(t); m_GeometryForInterpolation->Map(pt2d, pt); if(first==false) { vec=pt-lastPt; m_Length+=vec.GetNorm(); } first=false; float pvtk[3]; itk2vtk(pt, pvtk); cellarray->InsertCellPoint(points->InsertNextPoint(pvtk)); lastPt = pt; } } } const mitk::Mesh *mitk::InterpolateLinesFilter::GetInput(void) { if (this->GetNumberOfInputs() < 1) { return 0; } return static_cast (this->ProcessObject::GetInput(0) ); } void mitk::InterpolateLinesFilter::SetInput(const mitk::Mesh *input) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(0, const_cast< mitk::Mesh * >( input ) ); } diff --git a/Modules/MitkExt/Algorithms/mitkPolygonToRingFilter.cpp b/Modules/MitkExt/Algorithms/mitkPolygonToRingFilter.cpp index 09c2cce12b..e3035df2c8 100644 --- a/Modules/MitkExt/Algorithms/mitkPolygonToRingFilter.cpp +++ b/Modules/MitkExt/Algorithms/mitkPolygonToRingFilter.cpp @@ -1,341 +1,341 @@ /*=================================================================== 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. ===================================================================*/ #include "mitkPolygonToRingFilter.h" #include "mitkMesh.h" #include "mitkSurface.h" #include "mitkPlaneGeometry.h" #include #include #include #include #include #include #include #include mitk::PolygonToRingFilter::PolygonToRingFilter() : m_RingRadius(3.5f), m_RingResolution(30), m_SplineResolution(20) { m_SplineX = vtkCardinalSpline::New(); m_SplineY = vtkCardinalSpline::New(); m_SplineZ = vtkCardinalSpline::New(); } mitk::PolygonToRingFilter::~PolygonToRingFilter() { m_SplineX->Delete(); m_SplineY->Delete(); m_SplineZ->Delete(); } void mitk::PolygonToRingFilter::GenerateOutputInformation() { mitk::Mesh::ConstPointer input = this->GetInput(); mitk::Surface::Pointer output = this->GetOutput(0); itkDebugMacro(<<"GenerateOutputInformation()"); if(input.IsNull()) return; output->SetGeometry(static_cast(input->GetGeometry()->Clone().GetPointer())); output->Expand( input->GetPointSetSeriesSize() ); } void mitk::PolygonToRingFilter::GenerateData() { mitk::Mesh::ConstPointer input = this->GetInput(); mitk::Surface::Pointer output = this->GetOutput(0); unsigned int t; for ( t = 0; t < input->GetPointSetSeriesSize(); ++t ) { vtkPolyData *polyData = vtkPolyData::New(); vtkPoints *vPoints = vtkPoints::New(); vtkCellArray *polys = vtkCellArray::New(); mitk::Mesh::PointType thisPoint; // iterate through all cells and build tubes Mesh::ConstCellIterator cellIt, cellEnd; cellEnd = input->GetMesh( t )->GetCells()->End(); for ( cellIt = input->GetMesh( t )->GetCells()->Begin(); cellIt != cellEnd; ++cellIt ) { m_PointList.clear(); m_VectorList.clear(); this->BuildPointAndVectorList( *cellIt->Value(), m_PointList, m_VectorList, t ); this->BuildVtkTube( vPoints, polys, m_PointList, m_VectorList ); } polyData->SetPoints( vPoints ); vPoints->Delete(); polyData->SetPolys( polys ); polys->Delete(); output->SetVtkPolyData( polyData, t ); polyData->Delete(); } } -//sl: Stern Letzter -//sc: Stern Current=aktueller Stern -//idmax: Id des Strahls des aktuellen Sterns (sc), der am besten zum ersten Strahl vom letzten Stern (sl) passt. -//last_p: Mittelpunkt des letzten Sterns -//cur_p: Mittelpunkt des aktuellen Sterns +//sl: last star +//sc: current star +//idmax: Id of the current star ray (sc), which matchs proberly to the first ray of the last star (sl). +//last_p: center of the last star +//cur_p: center of the current star void mitk::PolygonToRingFilter::DrawCyl(vtkPoints *vPoints, vtkCellArray *polys, VectorListType &sl, VectorListType &sc, int idmax, Point3D & last_p, Point3D & cur_p) { unsigned int i; - //jetzt haben wir alles: sl0 wird mit sc->at(idmax) verbunden usw. + //now we finished:sl0 will be connected with sc->at(idmax) VectorListType::iterator slit=sl.begin(), scit=sc.begin(), scend=sc.end(); scit+=idmax; Point3D a,b; Point3D a_first,b_first; int a_firstID = 0, b_firstID = 0; vtkIdType front[4]; for(i=0;iInsertNextPoint(v0[0],v0[1],v0[2]); front[2]=vPoints->InsertNextPoint(v1[0],v1[1],v1[2]); front[1]=vPoints->InsertNextPoint(v2[0],v2[1],v2[2]); front[0]=vPoints->InsertNextPoint(v3[0],v3[1],v3[2]); polys->InsertNextCell( (vtkIdType) 4, front ); if(i==1) { a_firstID=front[3]; b_firstID=front[2]; //continue; } } ++slit; ++scit; if(scit==scend) scit=sc.begin(); } front[3]=front[0]; front[2]=front[1]; front[1]=b_firstID; front[0]=a_firstID; polys->InsertNextCell( 4, front ); } void mitk::PolygonToRingFilter::BuildVtkTube(vtkPoints *vPoints, vtkCellArray *polys, PointListType& ptList, VectorListType& vecList) { PointListType::iterator pit = ptList.begin(), pend = ptList.end(); VectorListType::iterator vit = vecList.begin(); Vector3D axis, last_v, next_v, s; Point3D cur_p,last_p; - //Listen für den Stern + //lists for the star VectorListType *sl, *sc, *swp, sfirst, buf1, buf2; sl=&buf1; sc=&buf2; Vector3D a,b; Matrix3D m; - //Initialisierung für ersten Punkt + //Initialization for the first point //alternative1: // last_v=*(vl.getLast()); next_v=*vit.current(); axis=last_v+next_v; s.cross(last_v,next_v); s.normalize(); //alternative2: // last_v=*(vl.getLast()); next_v=*vit.current(); s.cross(last_v,next_v); s.normalize(); // axis=next_v-last_v; axis.normalize(); aa.set(s, M_PI/2.0); m.set(aa); m.transform(&axis); //alternative3: last_v=vecList.back(); next_v=*vit; s.SetVnlVector( vnl_cross_3d(last_v.GetVnlVector(),next_v.GetVnlVector()) ); s.Normalize(); a=last_v; b=next_v; a.Normalize(); b.Normalize(); axis=a+b; axis.Normalize(); - //Stern am ersten Punkt aufbauen + //build the star at the first point m = vnl_quaternion(axis.GetVnlVector(),2*vnl_math::pi/(double)m_RingResolution).rotation_matrix_transpose(); unsigned int i; for(i=0;ibegin()); m = vnl_quaternion(axis.GetVnlVector(),2*vnl_math::pi/(double)m_RingResolution).rotation_matrix_transpose(); for(i=0;ipush_back(s); double tmp=s*sl0; if(tmp>max) { max=tmp; idmax=i; } s=m*s; } - //sl: Stern Letzter - //sc: Stern Current=aktueller Stern - //idmax: Id des Strahls des aktuellen Sterns (sc), der am besten zum ersten Strahl vom letzten Stern (sl) passt. - //last_p: Mittelpunkt des letzten Sterns - //cur_p: Mittelpunkt des aktuellen Sterns + //sl: last star + //sc: current star + //idmax: Id of the current star ray (sc), which matchs proberly to the first ray of the last star (sl). + //last_p: center of the last star + //cur_p: center of the current star DrawCyl(vPoints, polys, *sl, *sc, idmax, last_p, cur_p); - //Übergang zum nächsten + //Crossover to the next last_p=cur_p; swp=sl; sl=sc; sc=swp; sc->clear(); } - //idmax für Verbindung ersten mit letztem ausrechnen: + //calcutate idmax for connection: double max=0; int idmax=0; Vector3D sl0=*(sl->begin()); for(i=0;imax) { max=tmp; idmax=i; } } cur_p=*ptList.begin(); DrawCyl(vPoints, polys, *sl, sfirst, idmax, last_p, cur_p); } void mitk::PolygonToRingFilter ::BuildPointAndVectorList( mitk::Mesh::CellType& cell, PointListType& ptList, VectorListType& vecList, int timeStep ) { // This method constructs a spline from the given point list and retrieves // a number of interpolated points from it to form a ring-like structure. // // To make the spline "closed", the end point is connected to the start // point. For ensuring smoothness at the start-end-point transition, the // (intrinsically non-circular) spline array is extended on both sides // by wrapping a number of points from the respective other side. // // The used VTK filters do principally support this kind of "closed" spline, // but it does not produce results as consistent as with the method used // here. Also, the spline class of VTK 4.4 has only poor support for // arbitrary parametric coordinates (t values in vtkSpline). VTK 5.0 has // better support, and also provides a new class vtkParametricSpline for // directly calculating 3D splines. // Remove points from previous call of this method m_SplineX->RemoveAllPoints(); m_SplineY->RemoveAllPoints(); m_SplineZ->RemoveAllPoints(); int numberOfPoints = cell.GetNumberOfPoints(); Mesh::PointType inputPoint; vtkFloatingPointType t, tStart(0), tEnd(0); // Add input points to the spline and assign each the parametric value t // derived from the point euclidean distances. int i; Mesh::PointIdIterator pit = cell.PointIdsEnd() - 3; for ( i = -3, t = 0.0; i < numberOfPoints + 3; ++i ) { if ( i == 0 ) { tStart = t; } if ( i == numberOfPoints ) { tEnd = t; } inputPoint = this->GetInput()->GetPoint( *pit, timeStep ); m_SplineX->AddPoint( t, inputPoint[0] ); m_SplineY->AddPoint( t, inputPoint[1] ); m_SplineZ->AddPoint( t, inputPoint[2] ); ++pit; if ( pit == cell.PointIdsEnd() ) { pit = cell.PointIdsBegin(); } t += inputPoint.EuclideanDistanceTo( this->GetInput()->GetPoint( *pit, timeStep ) ); } // Evaluate the spline for the desired number of points // (number of input points) * (spline resolution) Point3D point, firstPoint, lastPoint; firstPoint.Fill(0); lastPoint.Fill(0); int numberOfSegments = numberOfPoints * m_SplineResolution; vtkFloatingPointType step = (tEnd - tStart) / numberOfSegments; for ( i = 0, t = tStart; i < numberOfSegments; ++i, t += step ) { FillVector3D( point, m_SplineX->Evaluate(t), m_SplineY->Evaluate(t), m_SplineZ->Evaluate(t) ); ptList.push_back( point ); if ( i == 0 ) { firstPoint = point; } else { vecList.push_back( point - lastPoint ); } lastPoint = point; } vecList.push_back( firstPoint - lastPoint ); } const mitk::Mesh *mitk::PolygonToRingFilter::GetInput(void) { if (this->GetNumberOfInputs() < 1) { return 0; } return static_cast (this->ProcessObject::GetInput(0) ); } void mitk::PolygonToRingFilter::SetInput(const mitk::Mesh *input) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(0, const_cast< mitk::Mesh * >( input ) ); } diff --git a/Modules/MitkExt/Algorithms/mitkVolumeVisualizationImagePreprocessor.cpp b/Modules/MitkExt/Algorithms/mitkVolumeVisualizationImagePreprocessor.cpp index 29be6d0282..13abc43f1f 100644 --- a/Modules/MitkExt/Algorithms/mitkVolumeVisualizationImagePreprocessor.cpp +++ b/Modules/MitkExt/Algorithms/mitkVolumeVisualizationImagePreprocessor.cpp @@ -1,652 +1,652 @@ /*=================================================================== 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. ===================================================================*/ #include "mitkVolumeVisualizationImagePreprocessor.h" #include #include #include #define VVP_INFO MITK_INFO << "Mem Usage: " << mitk::MemoryUtilities::GetProcessMemoryUsage() << " " namespace mitk { VolumeVisualizationImagePreprocessor::VolumeVisualizationImagePreprocessor() : m_OutOfLiverValue(-512), m_surfaceValue(-256), m_realSurfaceValue(0), m_EstimatedThreshold( 150.0 ), m_MinThreshold( 0.0 ), m_MaxThreshold( 250.0 ) { } VolumeVisualizationImagePreprocessor::~VolumeVisualizationImagePreprocessor() { } TransferFunction::Pointer VolumeVisualizationImagePreprocessor::GetInitialTransferFunction( ) { int treshold = m_EstimatedThreshold; double opacity = 0.005; double maskValue = m_OutOfLiverValue; double surfaceValue = m_surfaceValue; double realSurfaceValue = m_realSurfaceValue; //double surfaceSteepness = 0.0; VVP_INFO << "using threshold of " << treshold << " and opacity of " << opacity; TransferFunction::Pointer tf = TransferFunction::New(); // grayvalue->opacity { vtkPiecewiseFunction *f=tf->GetScalarOpacityFunction(); f->RemoveAllPoints(); f->AddPoint(maskValue,0); f->AddPoint(maskValue+1,0); f->AddPoint(surfaceValue,0.05); f->AddPoint(realSurfaceValue,opacity); f->AddPoint(treshold-1,opacity); f->AddPoint(treshold+4,0.8); f->AddPoint(m_MaxThreshold+1,0.8); f->ClampingOn(); f->Modified(); } // gradient at grayvalue->opacity { vtkPiecewiseFunction *f=tf->GetGradientOpacityFunction(); f->RemoveAllPoints(); f->AddPoint( -1000.0, 1.0 ); f->AddPoint( 1000, 1.0 ); f->ClampingOn(); f->Modified(); } // grayvalue->color { vtkColorTransferFunction *ctf=tf->GetColorTransferFunction(); ctf->RemoveAllPoints(); ctf->AddRGBPoint( maskValue, 0.5, 0.0, 0.0 ); ctf->AddRGBPoint( maskValue+1, 0.5, 0.0, 0.0 ); ctf->AddRGBPoint( surfaceValue, 1.0, 0.0, 0.0 ); //0.5 ctf->AddRGBPoint( realSurfaceValue, 0.2, 0.0, 0.0 ); ctf->AddRGBPoint( treshold-32, 0.2, 0.0, 0.0 ); ctf->AddRGBPoint( treshold, 251/255.0, 1.0, 0.0 ); ctf->AddRGBPoint( m_MaxThreshold+1, 251/255.0, 1.0, 0.0 ); ctf->ClampingOn(); ctf->Modified(); } m_LastUsedTreshold = treshold; return tf; } void VolumeVisualizationImagePreprocessor::UpdateTransferFunction( TransferFunction::Pointer tf, int treshold ) { double opacity = 0.005; //double maskValue = m_OutOfLiverValue; //double surfaceValue = m_surfaceValue; //double realSurfaceValue = m_realSurfaceValue; //double surfaceSteepness = 0.0; //VVP_INFO << "changing to threshold of " << treshold << " and opacity of " << opacity; // grayvalue->opacity { vtkPiecewiseFunction *f=tf->GetScalarOpacityFunction(); f->RemovePoint( m_LastUsedTreshold-1 ); f->AddPoint(treshold-1,opacity); f->RemovePoint( m_LastUsedTreshold+4 ); f->AddPoint(treshold+4,0.8); } // grayvalue->color { vtkColorTransferFunction *ctf=tf->GetColorTransferFunction(); ctf->RemovePoint( m_LastUsedTreshold-32 ); ctf->AddRGBPoint( treshold-32, 0.2, 0.0, 0.0 ); ctf->RemovePoint( m_LastUsedTreshold ); ctf->AddRGBPoint( treshold, 251/255.0, 1.0, 0.0 ); } m_LastUsedTreshold = treshold; } VolumeVisualizationImagePreprocessor::LabelImage::Pointer VolumeVisualizationImagePreprocessor::ConnectComponents(BinImage::Pointer src) { VVP_INFO << "Connect Components..."; LabelImage::Pointer dst = LabelImage::New(); typedef itk::ConnectedComponentImageFilter< BinImage, LabelImage > myFilterType; myFilterType::Pointer myFilter = myFilterType::New(); myFilter->SetInput(src); myFilter->Update(); dst = myFilter->GetOutput(); dst->DisconnectPipeline(); return dst; } VolumeVisualizationImagePreprocessor::BinImage::Pointer VolumeVisualizationImagePreprocessor::Threshold(CTImage::Pointer src, int threshold) { VVP_INFO << "thresholding..."; BinImage::Pointer dst = BinImage::New(); typedef itk::ThresholdLabelerImageFilter< CTImage, BinImage > myFilterType; myFilterType::Pointer myFilter = myFilterType::New(); myFilter->SetInput(src); myFilterType::ThresholdVector tv; tv.push_back(threshold); myFilter->SetThresholds(tv); myFilter->Update(); dst = myFilter->GetOutput(); dst->DisconnectPipeline(); return dst; } VolumeVisualizationImagePreprocessor::LabelImage::Pointer VolumeVisualizationImagePreprocessor::RelabelComponents(LabelImage::Pointer src) { VVP_INFO << "Relabeling Components..."; LabelImage::Pointer dst = LabelImage::New(); typedef itk::RelabelComponentImageFilter< LabelImage, LabelImage > myFilterType; myFilterType::Pointer myFilter = myFilterType::New(); myFilter->SetInput(src); myFilter->Update(); dst = myFilter->GetOutput(); dst->DisconnectPipeline(); return dst; } VolumeVisualizationImagePreprocessor::BinImage::Pointer VolumeVisualizationImagePreprocessor::Dilate(BinImage::Pointer src) { VVP_INFO << "Dilating..."; BinImage::Pointer dst = BinImage::New(); typedef itk::BinaryDilateImageFilter< BinImage, BinImage,itk::BinaryBallStructuringElement< unsigned char, 3> > BinaryDilateImageType; BinaryDilateImageType::KernelType myKernel; myKernel.SetRadius(1); myKernel.CreateStructuringElement(); BinaryDilateImageType::Pointer DilateFilter = BinaryDilateImageType::New(); DilateFilter->SetInput(src); DilateFilter->SetKernel(myKernel); DilateFilter->SetDilateValue(1); //to be dilated to DilateFilter->Update(); dst = DilateFilter->GetOutput(); dst->DisconnectPipeline(); return dst; } VolumeVisualizationImagePreprocessor::BinImage::Pointer VolumeVisualizationImagePreprocessor::Erode(BinImage::Pointer src) { VVP_INFO << "Eroding..."; BinImage::Pointer dst = BinImage::New(); typedef itk::BinaryErodeImageFilter< BinImage, BinImage,itk::BinaryBallStructuringElement< unsigned char, 3> > BinaryErodeImageType; BinaryErodeImageType::KernelType myKernel; myKernel.SetRadius(1); myKernel.CreateStructuringElement(); BinaryErodeImageType::Pointer ErodeFilter = BinaryErodeImageType::New(); ErodeFilter->SetInput(src); ErodeFilter->SetKernel(myKernel); ErodeFilter->SetErodeValue(0); //to be Eroded to ErodeFilter->Update(); dst = ErodeFilter->GetOutput(); dst->DisconnectPipeline(); return dst; } VolumeVisualizationImagePreprocessor::CTImage::Pointer VolumeVisualizationImagePreprocessor::Gaussian(CTImage::Pointer src) { VVP_INFO << "Gaussian..."; typedef itk::DiscreteGaussianImageFilter< CTImage, CTImage> GaussianFilterType; GaussianFilterType::Pointer gaussianFilter = GaussianFilterType::New(); gaussianFilter->SetInput( src ); gaussianFilter->SetVariance( 1 ); // gaussianFilter->SetMaximumError( 0.1 ); gaussianFilter->SetMaximumKernelWidth ( 8 ); gaussianFilter->UpdateLargestPossibleRegion(); CTImage::Pointer dst = gaussianFilter->GetOutput(); dst->DisconnectPipeline(); return dst; } VolumeVisualizationImagePreprocessor::CTImage::Pointer VolumeVisualizationImagePreprocessor::Crop(VolumeVisualizationImagePreprocessor::CTImage::Pointer src ) { VVP_INFO << "Cropping 16bit..."; typedef itk::RegionOfInterestImageFilter FilterType; FilterType::Pointer cropFilter = FilterType::New(); cropFilter->SetInput( src ); CTImage::RegionType region; CTImage::SizeType size; CTImage::IndexType index; index.SetElement(0,m_MinX); index.SetElement(1,m_MinY); index.SetElement(2,m_MinZ); size.SetElement(0,m_MaxX-m_MinX+1); size.SetElement(1,m_MaxY-m_MinY+1); size.SetElement(2,m_MaxZ-m_MinZ+1); region.SetIndex(index); region.SetSize(size); cropFilter->SetRegionOfInterest(region); cropFilter->Update(); CTImage::Pointer dst = cropFilter->GetOutput(); dst->DisconnectPipeline(); return dst; } VolumeVisualizationImagePreprocessor::BinImage::Pointer VolumeVisualizationImagePreprocessor::Crop(VolumeVisualizationImagePreprocessor::BinImage::Pointer src ) { VVP_INFO << "Cropping 8bit..."; typedef itk::RegionOfInterestImageFilter FilterType; FilterType::Pointer cropFilter = FilterType::New(); cropFilter->SetInput( src ); BinImage::RegionType region; BinImage::SizeType size; BinImage::IndexType index; index.SetElement(0,m_MinX); index.SetElement(1,m_MinY); index.SetElement(2,m_MinZ); size.SetElement(0,m_MaxX-m_MinX+1); size.SetElement(1,m_MaxY-m_MinY+1); size.SetElement(2,m_MaxZ-m_MinZ+1); region.SetIndex(index); region.SetSize(size); cropFilter->SetRegionOfInterest(region); cropFilter->Update(); BinImage::Pointer dst = cropFilter->GetOutput(); dst->DisconnectPipeline(); return dst; } /* CTImage::Pointer CTImageWork = CTImage::New(); CastToItkImage( imageOrg, CTImageWork ); BinImage::Pointer BinImageMask = BinImage::New(); CastToItkImage( imageMask, BinImageMask ); BinImage::Pointer BinImageMaskDilate = BinImage::New(); BinImage::Pointer BinImageMaskErode = BinImage::New(); */ int mitk::VolumeVisualizationImagePreprocessor::GetHistogrammValueFromBottom( double part ) { int unteren = total * part; for( int r = -32768 ; r <= 32767 ; r++ ) if( (unteren -= histogramm[32768+(int)r]) <= 0 ) return r; return 0; // will be never reached } int mitk::VolumeVisualizationImagePreprocessor::GetHistogrammValueFromTop( double part ) { int oberen = total * part; for( int r = 32767 ; r >= -32768 ; r-- ) if( (oberen -= histogramm[32768+(int)r]) <= 0 ) return r; return 0; // will be never reached } void VolumeVisualizationImagePreprocessor::DetermineBoundingBox( BinImage::Pointer mask ) { VVP_INFO << "determining Bounding Box..."; BinIteratorIndexType maskIt( mask, mask->GetRequestedRegion() ); maskIt.GoToBegin(); int totalMinX; int totalMinY; int totalMinZ; int totalMaxX; int totalMaxY; int totalMaxZ; // Initialize Bounding Box { m_MinX=m_MinY=m_MinZ = 1000000; m_MaxX=m_MaxY=m_MaxZ = -1000000; totalMinX=totalMinY=totalMinZ = 1000000; totalMaxX=totalMaxY=totalMaxZ = -1000000; } while ( ! maskIt.IsAtEnd() ) { BinIteratorIndexType::IndexType idx = maskIt.GetIndex(); int x=idx.GetElement(0); int y=idx.GetElement(1); int z=idx.GetElement(2); if(xtotalMaxX) totalMaxX=x; if(y>totalMaxY) totalMaxY=y; if(z>totalMaxZ) totalMaxZ=z; if(maskIt.Get()) { if(xm_MaxX) m_MaxX=x; if(y>m_MaxY) m_MaxY=y; if(z>m_MaxZ) m_MaxZ=z; } ++maskIt; } int border = 3; m_MinX -= border; if(m_MinX < totalMinX ) m_MinX = totalMinX; m_MinY -= border; if(m_MinY < totalMinY ) m_MinY = totalMinY; m_MinZ -= border; if(m_MinZ < totalMinZ ) m_MinZ = totalMinZ; m_MaxX += border; if(m_MaxX > totalMaxX ) m_MaxX = totalMaxX; m_MaxY += border; if(m_MaxY > totalMaxY ) m_MaxY = totalMaxY; m_MaxZ += border; if(m_MaxZ > totalMaxZ ) m_MaxZ = totalMaxZ; VVP_INFO << "Bounding box" << " m_MinX: " << m_MinX << " m_MaxX: " << m_MaxX << "\n m_MinY: " << m_MinY << " m_MaxY: " << m_MaxY << "\n m_MinZ: " << m_MinZ << " m_MaxZ: " << m_MaxZ; } mitk::VolumeVisualizationImagePreprocessor::CTImage::Pointer VolumeVisualizationImagePreprocessor::Composite( CTImage::Pointer work, BinImage::Pointer mask, BinImage::Pointer dilated, BinImage::Pointer eroded) { VVP_INFO << "Compositing..."; /* itk::OrImageFilter::Pointer nullFilter= itk::OrImageFilter::New(); nullFilter->SetInput1( input ); nullFilter->SetInput2( input ); nullFilter->UpdateLargestPossibleRegion(); CTImage::Pointer work = nullFilter->GetOutput(); */ CTIteratorIndexType workIt( work, work->GetRequestedRegion() ); BinIteratorType maskIt( mask, mask->GetRequestedRegion() ); BinIteratorType dilateIt( dilated, dilated->GetRequestedRegion() ); BinIteratorType erodeIt( eroded, eroded->GetRequestedRegion() ); workIt.GoToBegin(); maskIt.GoToBegin(); dilateIt.GoToBegin(); erodeIt.GoToBegin(); double sum=0; int num=0; double sumIn=0; int numIn=0; int _min=32767,_max=-32768; total=0; memset(histogramm,0,sizeof(int)*65536); while ( ! ( workIt.IsAtEnd() || maskIt.IsAtEnd() || dilateIt.IsAtEnd() || erodeIt.IsAtEnd() ) ) { int value = workIt.Get(); unsigned char mask = maskIt.Get(); unsigned char dilate = dilateIt.Get(); unsigned char erode = erodeIt.Get(); -//baut Histogramm auf vom Leberinneren + //build barchart of internal of the liver if(mask != 0) { sumIn+=value; numIn++; histogramm[32768+(int)value]++; total++; } -//Mittelwert der äußeren Schicht + //average of the exterior layer if(erode != 0 && mask != 0 ) { sum+=value; num++; if(value>_max) _max=value; if(value<_min) _min=value; } - //markiere Leberoberfläche mit -1024 und update bounding box + //mark the surface of the liver with -1024 and update bounding box if(erode == 0 && dilate != 0 ) { value = -1024; } - else if( erode != 0 && mask != 0 )//Leberinneres, behalte Grauwert bei + else if( erode != 0 && mask != 0 )//Keep the gray values of internal of the liver { } - else//markiere äußeres mit -2048 + else//mark the exterior with -2048 { value = -2048; } workIt.Set(value); ++workIt; ++maskIt; ++dilateIt; ++erodeIt; } VVP_INFO << "liver consists of " << total << " samples."; m_GreatestStructureThreshold = GetHistogrammValueFromTop(0.20); m_EstimatedThreshold = GetHistogrammValueFromTop(0.10); m_MaxThreshold=GetHistogrammValueFromTop(0.001); m_MinThreshold=GetHistogrammValueFromBottom(0.20); VVP_INFO << "threshold range: (" << m_MinThreshold << ";" << m_MaxThreshold << ") estimated vessel threshold: " << m_EstimatedThreshold ; VVP_INFO << "m_GreatestStructureThreshold: " << m_GreatestStructureThreshold; // BinImage::Pointer binImageThreshold= Threshold(work,m_GreatestStructureThreshold ); // LabelImage::Pointer LabelImageunsorted=ConnectComponents(binImageThreshold); // LabelImage::Pointer LabelImageSorted= RelabelComponents(LabelImageunsorted); if(num>0) m_realSurfaceValue=sum/num; else m_realSurfaceValue=0; if(numIn>0) m_realInLiverValue=sumIn/numIn; else m_realInLiverValue=0; m_surfaceValue = _min - 40; m_OutOfLiverValue = m_surfaceValue - 40; // LabelIteratorType labelIt( LabelImageSorted, LabelImageSorted->GetRequestedRegion() ); workIt.GoToBegin(); // labelIt.GoToBegin(); //int numGesetzt=0; //int numGelassen=0; while ( ! workIt.IsAtEnd() ) { int value = workIt.Get(); // int label = labelIt.Get(); if(value == -1024 ) { value = m_surfaceValue; } else if( value == -2048 ) { value = m_OutOfLiverValue; } else - {//innerhalb der Leber - //Label ungleich 1 -->value auf min setzen + {//In the space of the liver + //Label unequal 1 --> set value on minimum /* if (label != 1){ numGesetzt++; value=m_realInLiverValue; } else { //value=m_EstimatedThreshold; numGelassen++; } */ } workIt.Set(value); ++workIt; // ++labelIt; } - //VVP_INFO << "gesetzt: " << numGesetzt << " --- gelassen: " << numGelassen; + //VVP_INFO << "set: " << numGesetzt << " --- unvaried: " << numGelassen; VVP_INFO << "OutOfLiver value: " << m_OutOfLiverValue; VVP_INFO << "surface value: " << m_surfaceValue; VVP_INFO << "real surface value: " << m_realSurfaceValue; VVP_INFO << "real inLiver value:" << m_realInLiverValue; work->DisconnectPipeline(); return work; } Image::Pointer VolumeVisualizationImagePreprocessor::Process( Image::Pointer m_originalCT, Image::Pointer m_originalLiverMask) { VVP_INFO << "Processing..."; // converting mitk image -> itk image CTImage::Pointer CTImageWork = CTImage::New(); CastToItkImage( m_originalCT, CTImageWork ); // converting mitk image -> itk image BinImage::Pointer BinImageMask = BinImage::New(); CastToItkImage( m_originalLiverMask, BinImageMask ); DetermineBoundingBox( BinImageMask ); if( m_MaxX < m_MinX || m_MaxY < m_MinY || m_MaxZ < m_MinZ ) return 0; CTImageWork = Gaussian(Crop( CTImageWork )); BinImageMask = Crop( BinImageMask ); CTImage::Pointer itkResult =Composite(CTImageWork,BinImageMask,Dilate(BinImageMask),Erode(BinImageMask)); mitk::Image::Pointer mitkResult= mitk::Image::New(); mitk::CastToMitkImage( itkResult, mitkResult ); //TODO here we can perhaps save memory VVP_INFO << "Finished..."; return mitkResult; } } diff --git a/Modules/MitkExt/Interactions/mitkTDMouseEventThrower.cpp b/Modules/MitkExt/Interactions/mitkTDMouseEventThrower.cpp index 3a01a2e2bc..bac5f67267 100644 --- a/Modules/MitkExt/Interactions/mitkTDMouseEventThrower.cpp +++ b/Modules/MitkExt/Interactions/mitkTDMouseEventThrower.cpp @@ -1,64 +1,64 @@ /*=================================================================== 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. ===================================================================*/ #include "mitkTDMouseEventThrower.h" #include "mitkTDMouseEvent.h" #include "mitkInteractionConst.h" #include "mitkVector.h" #include "mitkGlobalInteraction.h" #include "mitkStateEvent.h" #include "mitkSpaceNavigatorDriver.h" mitk::TDMouseEventThrower * mitk::TDMouseEventThrower::GetInstance() { - //instance wird nicht initialisiert und kommt mit 0 zurück! + //instance will not be initialize and return 0 static TDMouseEventThrower instance; return &instance; } mitk::TDMouseEventThrower::TDMouseEventThrower() { //init the driver SpaceNavigatorDriver* spaceNavigatorDriver = SpaceNavigatorDriver::GetInstance(); } mitk::TDMouseEventThrower::~TDMouseEventThrower() { } void mitk::TDMouseEventThrower::DeviceChange (long device, long keys, long programmableKeys) { } void mitk::TDMouseEventThrower::KeyDown (int keyCode) { //send the informations to GlobalInteraction mitk::Event* e = new mitk::Event(NULL, mitk::Type_TDMouseKeyDown, mitk::BS_LeftButton, keyCode, mitk::Key_none); mitk::StateEvent* se = new mitk::StateEvent(mitk::EIDTDMOUSEKEYDOWN, e); mitk::GlobalInteraction::GetInstance()->HandleEvent(se); } void mitk::TDMouseEventThrower::KeyUp (int keyCode) { } void mitk::TDMouseEventThrower::SensorInput( mitk::Vector3D translation, mitk::Vector3D rotation, mitk::ScalarType angle) { mitk::TDMouseEvent* e = new mitk::TDMouseEvent(mitk::BS_NoButton, translation, rotation, angle); mitk::StateEvent* se = new mitk::StateEvent(mitk::EIDTDMOUSEINPUT, e); mitk::GlobalInteraction::GetInstance()->HandleEvent(se); } diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/surfaceutilities/mitkTargetPointsCalculator.cpp b/Plugins/org.mitk.gui.qt.examples/src/internal/surfaceutilities/mitkTargetPointsCalculator.cpp index 0e3761178a..249d1ee50c 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/surfaceutilities/mitkTargetPointsCalculator.cpp +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/surfaceutilities/mitkTargetPointsCalculator.cpp @@ -1,270 +1,270 @@ /*=================================================================== 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 headers #include "mitkTargetPointsCalculator.h" #include #include #include "mitkSurfaceToPointSetFilter.h" //itk headers #include #include #define ROUND(a) ((a)>0 ? (int)((a)+0.5) : -(int)(0.5-(a))) typedef itk::Image ImageType; typedef itk::ImageRegionIterator IteratorType; mitk::TargetPointsCalculator::TargetPointsCalculator() { //set default values m_InterPointDistance = 20; m_ErrorMessage = ""; m_Method = mitk::TargetPointsCalculator::EvenlyDistributedTargetPoints; } mitk::TargetPointsCalculator::~TargetPointsCalculator() { } void mitk::TargetPointsCalculator::SetInput(mitk::Surface::Pointer input) { m_Input = input; } bool mitk::TargetPointsCalculator::DoCalculate() { if (m_Input.IsNull()) { m_ErrorMessage = "Error in TargetPointsCalculator: please set input first!"; return false; } if (m_Method == mitk::TargetPointsCalculator::EvenlyDistributedTargetPoints) { mitk::Image::Pointer binaryImage = this->CreateBinaryImage(m_Input); this->m_Output = this->CreateTargetPoints(binaryImage); } else if (m_Method == mitk::TargetPointsCalculator::OneTargetPointInCenterOfGravity) { this->m_Output = this->CreateTargetPointInCOG(m_Input); } else { return false; } return true; } void mitk::TargetPointsCalculator::SetTargetPointCalculationMethod(TargetPointCalculationMethod method) { m_Method = method; } mitk::PointSet::Pointer mitk::TargetPointsCalculator::GetOutput() { return m_Output; } std::string mitk::TargetPointsCalculator::GetErrorMessage() { return m_ErrorMessage; } mitk::Image::Pointer mitk::TargetPointsCalculator::CreateBinaryImage(mitk::Surface::Pointer input) { //################################################################################ //###################### create binary image out of stl ########################## //################################################################################ typedef unsigned char PixelType; // get bounding box of current surface const mitk::BoundingBox* boundingBox = this->m_Input->GetGeometry()->GetBoundingBox(); mitk::BoundingBox::PointType minimum = boundingBox->GetMinimum(); mitk::BoundingBox::PointType maximum = boundingBox->GetMaximum(); // calculate image parameters float spacingFactor = 1; unsigned int dim[3]; dim[0] = ROUND(spacingFactor*(abs(maximum[0]-minimum[0]))); dim[1] = ROUND(spacingFactor*(abs(maximum[1]-minimum[1]))); dim[2] = ROUND(spacingFactor*(abs(maximum[2]-minimum[2]))); float* origin = new float[3]; origin[0] = minimum[0]; origin[1] = minimum[1]; origin[2] = minimum[2]; itk::Size<3> size = {dim[0],dim[1],dim[2]}; // create white itk image ImageType::Pointer image = ImageType::New(); ImageType::IndexType start; start[0] = 0; start[1] = 0; start[2] = 0; ImageType::SizeType imageSize; imageSize[0] = maximum[0]-minimum[0]+20; imageSize[1] = maximum[1]-minimum[1]+20; imageSize[2] = maximum[2]-minimum[2]+20; ImageType::RegionType region; region.SetSize(imageSize); region.SetIndex(start); image->SetRegions(region); image->Allocate(); // set all pixel values to 1 PixelType pixel = 1; IteratorType iterator( image, image->GetRequestedRegion()); iterator.GoToBegin(); while (!iterator.IsAtEnd()) { iterator.Set(pixel); ++iterator; } // convert to mitk image mitk::Image::Pointer mitkImage; mitk::CastToMitkImage(image,mitkImage); mitk::Point3D orig; orig[0] = minimum[0]-10; orig[1] = minimum[1]-10; orig[2] = minimum[2]-10; mitkImage->SetOrigin(orig); mitkImage->UpdateOutputInformation(); mitk::SurfaceToImageFilter::Pointer surfaceToImage = mitk::SurfaceToImageFilter::New(); surfaceToImage->SetImage(mitkImage); surfaceToImage->SetInput(m_Input); surfaceToImage->MakeOutputBinaryOn(); surfaceToImage->Update(); return surfaceToImage->GetOutput(); } mitk::PointSet::Pointer mitk::TargetPointsCalculator::CreateTargetPoints(mitk::Image::Pointer binaryImage) { - //Bounding-Box besimmten: + //determine bounding box: ImageType::Pointer itkImage = ImageType::New(); mitk::CastToItkImage(binaryImage, itkImage); itk::Index<3> begin = {{0,0,0}}; itk::Index<3> end = {{binaryImage->GetDimension(0),binaryImage->GetDimension(1),binaryImage->GetDimension(2)}}; mitk::Point3D beginWorld; mitk::Point3D endWorld; itkImage->TransformIndexToPhysicalPoint(begin, beginWorld); itkImage->TransformIndexToPhysicalPoint(end, endWorld); - //ende Bounding Box bestimmen + //determine end of bounding box //Pointset initialisieren mitk::PointSet::Pointer returnValue = mitk::PointSet::New(); - int m = 0; //Laufvariable für Pointset-ID + int m = 0; //control value for Pointset-ID - //Abstand der Punkte initialisieren (in mm) + //initialize the distance of the points (in mm) int abstand = m_InterPointDistance; //######################################################### - //############## BERECHNUNG DER PUNKTE #################### + //############## calculation of the points#################### //######################################################### - //Gatter aufbauen: + //build up gate: mitk::Point3D p; for(int i=RoundUpToGatter(beginWorld.GetElement(0),abstand); i(p, i,j,k); //if it is inside the main structure if (this->isInside(itkImage,p) ) { returnValue->SetPoint(m, p); m++; } } } } return returnValue; } int mitk::TargetPointsCalculator::RoundUpToGatter(int i, int gatter) { int centimeters = RoundUpToCentimeters(i); int mod = centimeters % gatter; int returnValue = centimeters+(gatter-mod); return returnValue; } int mitk::TargetPointsCalculator::RoundUpToCentimeters(int i) { int returnValue = (i+9.999) / 10; returnValue = returnValue * 10; return returnValue; } bool mitk::TargetPointsCalculator::isInside(ImageType::Pointer currentImageAsitkImage, mitk::Point3D p) { itk::Index<3> contInd; if (currentImageAsitkImage->TransformPhysicalPointToIndex(p, contInd)) { unsigned short pixel = currentImageAsitkImage->GetPixel(contInd); if (pixel==1) {return true;} else return false; } else return false; } void mitk::TargetPointsCalculator::SetInterPointDistance(int d) { this->m_InterPointDistance = d; } mitk::PointSet::Pointer mitk::TargetPointsCalculator::CreateTargetPointInCOG(mitk::Surface::Pointer surface) { mitk::PointSet::Pointer returnValue = mitk::PointSet::New(); //convert surface to point set mitk::SurfaceToPointSetFilter::Pointer mySurfaceToPointSetFilter = mitk::SurfaceToPointSetFilter::New(); mySurfaceToPointSetFilter->SetInput(surface); mySurfaceToPointSetFilter->Update(); mitk::PointSet::Pointer ptSet = mySurfaceToPointSetFilter->GetOutput(); //calculate CoG mitk::Point3D CoG; CoG.Fill(0); for (int i=0; iGetSize(); i++) { CoG[0] += ptSet->GetPoint(i)[0]; CoG[1] += ptSet->GetPoint(i)[1]; CoG[2] += ptSet->GetPoint(i)[2]; } CoG[0] /= ptSet->GetSize(); CoG[1] /= ptSet->GetSize(); CoG[2] /= ptSet->GetSize(); //update return value returnValue->InsertPoint(0,CoG); return returnValue; } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp index b6acb9ba4d..6591cb5fb8 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp @@ -1,1190 +1,1190 @@ /*=================================================================== 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. ===================================================================*/ #include "QmitkExtWorkbenchWindowAdvisor.h" #include "QmitkExtActionBarAdvisor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // UGLYYY #include "internal/QmitkExtWorkbenchWindowAdvisorHack.h" #include "internal/QmitkCommonExtPlugin.h" #include "mitkUndoController.h" #include "mitkVerboseLimitedLinearUndo.h" #include #include #include #include QmitkExtWorkbenchWindowAdvisorHack * QmitkExtWorkbenchWindowAdvisorHack::undohack = new QmitkExtWorkbenchWindowAdvisorHack(); QString QmitkExtWorkbenchWindowAdvisor::QT_SETTINGS_FILENAME = "QtSettings.ini"; class PartListenerForTitle: public berry::IPartListener { public: PartListenerForTitle(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) { } Events::Types GetPartEventTypes() const { return Events::ACTIVATED | Events::BROUGHT_TO_TOP | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartActivated(berry::IWorkbenchPartReference::Pointer ref) { if (ref.Cast ()) { windowAdvisor->UpdateTitle(false); } } void PartBroughtToTop(berry::IWorkbenchPartReference::Pointer ref) { if (ref.Cast ()) { windowAdvisor->UpdateTitle(false); } } void PartClosed(berry::IWorkbenchPartReference::Pointer /*ref*/) { windowAdvisor->UpdateTitle(false); } void PartHidden(berry::IWorkbenchPartReference::Pointer ref) { if (!windowAdvisor->lastActiveEditor.Expired() && ref->GetPart(false) == windowAdvisor->lastActiveEditor.Lock()) { windowAdvisor->UpdateTitle(true); } } void PartVisible(berry::IWorkbenchPartReference::Pointer ref) { if (!windowAdvisor->lastActiveEditor.Expired() && ref->GetPart(false) == windowAdvisor->lastActiveEditor.Lock()) { windowAdvisor->UpdateTitle(false); } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; }; class PartListenerForImageNavigator: public berry::IPartListener { public: PartListenerForImageNavigator(QAction* act) : imageNavigatorAction(act) { } Events::Types GetPartEventTypes() const { return Events::OPENED | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartOpened(berry::IWorkbenchPartReference::Pointer ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(true); } } void PartClosed(berry::IWorkbenchPartReference::Pointer ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(false); } } void PartVisible(berry::IWorkbenchPartReference::Pointer ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(true); } } void PartHidden(berry::IWorkbenchPartReference::Pointer ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(false); } } private: QAction* imageNavigatorAction; }; class PerspectiveListenerForTitle: public berry::IPerspectiveListener { public: PerspectiveListenerForTitle(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa), perspectivesClosed(false) { } Events::Types GetPerspectiveEventTypes() const { return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED // remove the following line when command framework is finished | Events::CLOSED | Events::OPENED; } void PerspectiveActivated(berry::IWorkbenchPage::Pointer /*page*/, berry::IPerspectiveDescriptor::Pointer /*perspective*/) { windowAdvisor->UpdateTitle(false); } void PerspectiveSavedAs(berry::IWorkbenchPage::Pointer /*page*/, berry::IPerspectiveDescriptor::Pointer /*oldPerspective*/, berry::IPerspectiveDescriptor::Pointer /*newPerspective*/) { windowAdvisor->UpdateTitle(false); } void PerspectiveDeactivated(berry::IWorkbenchPage::Pointer /*page*/, berry::IPerspectiveDescriptor::Pointer /*perspective*/) { windowAdvisor->UpdateTitle(false); } void PerspectiveOpened(berry::IWorkbenchPage::Pointer /*page*/, berry::IPerspectiveDescriptor::Pointer /*perspective*/) { if (perspectivesClosed) { QListIterator i(windowAdvisor->viewActions); while (i.hasNext()) { i.next()->setEnabled(true); } //GetViewRegistry()->Find("org.mitk.views.imagenavigator"); if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) { windowAdvisor->openDicomEditorAction->setEnabled(true); } windowAdvisor->fileSaveProjectAction->setEnabled(true); windowAdvisor->closeProjectAction->setEnabled(true); windowAdvisor->undoAction->setEnabled(true); windowAdvisor->redoAction->setEnabled(true); windowAdvisor->imageNavigatorAction->setEnabled(true); windowAdvisor->resetPerspAction->setEnabled(true); if( windowAdvisor->GetShowClosePerspectiveMenuItem() ) { windowAdvisor->closePerspAction->setEnabled(true); } } perspectivesClosed = false; } void PerspectiveClosed(berry::IWorkbenchPage::Pointer /*page*/, berry::IPerspectiveDescriptor::Pointer /*perspective*/) { berry::IWorkbenchWindow::Pointer wnd = windowAdvisor->GetWindowConfigurer()->GetWindow(); bool allClosed = true; if (wnd->GetActivePage()) { std::vector perspectives(wnd->GetActivePage()->GetOpenPerspectives()); allClosed = perspectives.empty(); } if (allClosed) { perspectivesClosed = true; QListIterator i(windowAdvisor->viewActions); while (i.hasNext()) { i.next()->setEnabled(false); } if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) { windowAdvisor->openDicomEditorAction->setEnabled(false); } windowAdvisor->fileSaveProjectAction->setEnabled(false); windowAdvisor->closeProjectAction->setEnabled(false); windowAdvisor->undoAction->setEnabled(false); windowAdvisor->redoAction->setEnabled(false); windowAdvisor->imageNavigatorAction->setEnabled(false); windowAdvisor->resetPerspAction->setEnabled(false); if( windowAdvisor->GetShowClosePerspectiveMenuItem() ) { windowAdvisor->closePerspAction->setEnabled(false); } } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; bool perspectivesClosed; }; class PerspectiveListenerForMenu: public berry::IPerspectiveListener { public: PerspectiveListenerForMenu(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) { } Events::Types GetPerspectiveEventTypes() const { return Events::ACTIVATED | Events::DEACTIVATED; } void PerspectiveActivated(berry::IWorkbenchPage::Pointer /*page*/, berry::IPerspectiveDescriptor::Pointer perspective) { QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()]; if (action) { action->setChecked(true); } } void PerspectiveDeactivated(berry::IWorkbenchPage::Pointer /*page*/, berry::IPerspectiveDescriptor::Pointer perspective) { QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()]; if (action) { action->setChecked(false); } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; }; QmitkExtWorkbenchWindowAdvisor::QmitkExtWorkbenchWindowAdvisor(berry::WorkbenchAdvisor* wbAdvisor, berry::IWorkbenchWindowConfigurer::Pointer configurer) : berry::WorkbenchWindowAdvisor(configurer), lastInput(0), wbAdvisor(wbAdvisor), showViewToolbar(true), showPerspectiveToolbar(false), showVersionInfo(true), showMitkVersionInfo(true), showViewMenuItem(true), showNewWindowMenuItem(false), showClosePerspectiveMenuItem(true), dropTargetListener(new QmitkDefaultDropTargetListener) { productName = QCoreApplication::applicationName().toStdString(); } berry::ActionBarAdvisor::Pointer QmitkExtWorkbenchWindowAdvisor::CreateActionBarAdvisor( berry::IActionBarConfigurer::Pointer configurer) { berry::ActionBarAdvisor::Pointer actionBarAdvisor( new QmitkExtActionBarAdvisor(configurer)); return actionBarAdvisor; } void* QmitkExtWorkbenchWindowAdvisor::CreateEmptyWindowContents(void* parent) { QWidget* parentWidget = static_cast(parent); QLabel* label = new QLabel(parentWidget); label->setText("No perspectives are open. Open a perspective in the Window->Open Perspective menu."); label->setContentsMargins(10,10,10,10); label->setAlignment(Qt::AlignTop); label->setEnabled(false); parentWidget->layout()->addWidget(label); return label; } void QmitkExtWorkbenchWindowAdvisor::ShowClosePerspectiveMenuItem(bool show) { showClosePerspectiveMenuItem = show; } bool QmitkExtWorkbenchWindowAdvisor::GetShowClosePerspectiveMenuItem() { return showClosePerspectiveMenuItem; } void QmitkExtWorkbenchWindowAdvisor::ShowNewWindowMenuItem(bool show) { showNewWindowMenuItem = show; } void QmitkExtWorkbenchWindowAdvisor::ShowViewToolbar(bool show) { showViewToolbar = show; } void QmitkExtWorkbenchWindowAdvisor::ShowViewMenuItem(bool show) { showViewMenuItem = show; } void QmitkExtWorkbenchWindowAdvisor::ShowPerspectiveToolbar(bool show) { showPerspectiveToolbar = show; } void QmitkExtWorkbenchWindowAdvisor::ShowVersionInfo(bool show) { showVersionInfo = show; } void QmitkExtWorkbenchWindowAdvisor::ShowMitkVersionInfo(bool show) { showMitkVersionInfo = show; } void QmitkExtWorkbenchWindowAdvisor::SetProductName(const std::string& product) { productName = product; } void QmitkExtWorkbenchWindowAdvisor::SetWindowIcon(const std::string& wndIcon) { windowIcon = wndIcon; } void QmitkExtWorkbenchWindowAdvisor::PostWindowCreate() { // very bad hack... berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); QMainWindow* mainWindow = static_cast (window->GetShell()->GetControl()); if (!windowIcon.empty()) { mainWindow->setWindowIcon(QIcon(QString::fromStdString(windowIcon))); } mainWindow->setContextMenuPolicy(Qt::PreventContextMenu); /*mainWindow->setStyleSheet("color: white;" "background-color: #808080;" "selection-color: #659EC7;" "selection-background-color: #808080;" " QMenuBar {" "background-color: #808080; }");*/ // ==== Application menu ============================ QMenuBar* menuBar = mainWindow->menuBar(); menuBar->setContextMenuPolicy(Qt::PreventContextMenu); QMenu* fileMenu = menuBar->addMenu("&File"); fileMenu->setObjectName("FileMenu"); QAction* fileOpenAction = new QmitkFileOpenAction(QIcon(":/org.mitk.gui.qt.ext/Load_48.png"), window); fileMenu->addAction(fileOpenAction); fileSaveProjectAction = new QmitkExtFileSaveProjectAction(window); fileSaveProjectAction->setIcon(QIcon(":/org.mitk.gui.qt.ext/Save_48.png")); fileMenu->addAction(fileSaveProjectAction); closeProjectAction = new QmitkCloseProjectAction(window); closeProjectAction->setIcon(QIcon(":/org.mitk.gui.qt.ext/Remove_48.png")); fileMenu->addAction(closeProjectAction); fileMenu->addSeparator(); QAction* fileExitAction = new QmitkFileExitAction(window); fileExitAction->setObjectName("QmitkFileExitAction"); fileMenu->addAction(fileExitAction); if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) { openDicomEditorAction = new QmitkOpenDicomEditorAction(QIcon(":/org.mitk.gui.qt.ext/dcm-icon.png"),window); } berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry(); const std::vector& viewDescriptors = viewRegistry->GetViews(); // another bad hack to get an edit/undo menu... QMenu* editMenu = menuBar->addMenu("&Edit"); undoAction = editMenu->addAction(QIcon(":/org.mitk.gui.qt.ext/Undo_48.png"), "&Undo", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onUndo()), QKeySequence("CTRL+Z")); undoAction->setToolTip("Undo the last action (not supported by all modules)"); redoAction = editMenu->addAction(QIcon(":/org.mitk.gui.qt.ext/Redo_48.png") , "&Redo", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onRedo()), QKeySequence("CTRL+Y")); redoAction->setToolTip("execute the last action that was undone again (not supported by all modules)"); imageNavigatorAction = new QAction(QIcon(":/org.mitk.gui.qt.ext/Slider.png"), "&Image Navigator", NULL); bool imageNavigatorViewFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.imagenavigator"); if (imageNavigatorViewFound) { QObject::connect(imageNavigatorAction, SIGNAL(triggered(bool)), QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onImageNavigator())); imageNavigatorAction->setCheckable(true); // add part listener for image navigator imageNavigatorPartListener = new PartListenerForImageNavigator(imageNavigatorAction); window->GetPartService()->AddPartListener(imageNavigatorPartListener); berry::IViewPart::Pointer imageNavigatorView = window->GetActivePage()->FindView("org.mitk.views.imagenavigator"); imageNavigatorAction->setChecked(false); if (imageNavigatorView) { bool isImageNavigatorVisible = window->GetActivePage()->IsPartVisible(imageNavigatorView); if (isImageNavigatorVisible) imageNavigatorAction->setChecked(true); } imageNavigatorAction->setToolTip("Open image navigator for navigating through image"); } // toolbar for showing file open, undo, redo and other main actions QToolBar* mainActionsToolBar = new QToolBar; mainActionsToolBar->setContextMenuPolicy(Qt::PreventContextMenu); #ifdef __APPLE__ mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon ); #else mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon ); #endif mainActionsToolBar->addAction(fileOpenAction); mainActionsToolBar->addAction(fileSaveProjectAction); mainActionsToolBar->addAction(closeProjectAction); mainActionsToolBar->addAction(undoAction); mainActionsToolBar->addAction(redoAction); if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) { mainActionsToolBar->addAction(openDicomEditorAction); } if (imageNavigatorViewFound) { mainActionsToolBar->addAction(imageNavigatorAction); } mainWindow->addToolBar(mainActionsToolBar); #ifdef __APPLE__ mainWindow->setUnifiedTitleAndToolBarOnMac(true); #endif // ==== Window Menu ========================== QMenu* windowMenu = menuBar->addMenu("Window"); if (showNewWindowMenuItem) { windowMenu->addAction("&New Window", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onNewWindow())); windowMenu->addSeparator(); } QMenu* perspMenu = windowMenu->addMenu("&Open Perspective"); QMenu* viewMenu; if (showViewMenuItem) { viewMenu = windowMenu->addMenu("Show &View"); viewMenu->setObjectName("Show View"); } windowMenu->addSeparator(); resetPerspAction = windowMenu->addAction("&Reset Perspective", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onResetPerspective())); if(showClosePerspectiveMenuItem) closePerspAction = windowMenu->addAction("&Close Perspective", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onClosePerspective())); windowMenu->addSeparator(); windowMenu->addAction("&Preferences...", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onEditPreferences()), QKeySequence("CTRL+P")); // fill perspective menu berry::IPerspectiveRegistry* perspRegistry = window->GetWorkbench()->GetPerspectiveRegistry(); QActionGroup* perspGroup = new QActionGroup(menuBar); std::vector perspectives( perspRegistry->GetPerspectives()); bool skip = false; for (std::vector::iterator perspIt = perspectives.begin(); perspIt != perspectives.end(); ++perspIt) { // if perspectiveExcludeList is set, it contains the id-strings of perspectives, which // should not appear as an menu-entry in the perspective menu if (perspectiveExcludeList.size() > 0) { for (unsigned int i=0; iGetId()) { skip = true; break; } } if (skip) { skip = false; continue; } } QAction* perspAction = new berry::QtOpenPerspectiveAction(window, *perspIt, perspGroup); mapPerspIdToAction.insert(std::make_pair((*perspIt)->GetId(), perspAction)); } perspMenu->addActions(perspGroup->actions()); // sort elements (converting vector to map...) std::vector::const_iterator iter; std::map VDMap; skip = false; for (iter = viewDescriptors.begin(); iter != viewDescriptors.end(); ++iter) { // if viewExcludeList is set, it contains the id-strings of view, which // should not appear as an menu-entry in the menu if (viewExcludeList.size() > 0) { for (unsigned int i=0; iGetId()) { skip = true; break; } } if (skip) { skip = false; continue; } } if ((*iter)->GetId() == "org.blueberry.ui.internal.introview") continue; if ((*iter)->GetId() == "org.mitk.views.imagenavigator") continue; std::pair p( (*iter)->GetLabel(), (*iter)); VDMap.insert(p); } // ================================================== // ==== Perspective Toolbar ================================== QToolBar* qPerspectiveToolbar = new QToolBar; if (showPerspectiveToolbar) { qPerspectiveToolbar->addActions(perspGroup->actions()); mainWindow->addToolBar(qPerspectiveToolbar); } else delete qPerspectiveToolbar; // ==== View Toolbar ================================== QToolBar* qToolbar = new QToolBar; std::map::const_iterator MapIter; for (MapIter = VDMap.begin(); MapIter != VDMap.end(); ++MapIter) { berry::QtShowViewAction* viewAction = new berry::QtShowViewAction(window, (*MapIter).second); viewActions.push_back(viewAction); if(showViewMenuItem) viewMenu->addAction(viewAction); if (showViewToolbar) { qToolbar->addAction(viewAction); } } if (showViewToolbar) { mainWindow->addToolBar(qToolbar); } else delete qToolbar; QSettings settings(GetQSettingsFile(), QSettings::IniFormat); mainWindow->restoreState(settings.value("ToolbarPosition").toByteArray()); // ==================================================== // ===== Help menu ==================================== QMenu* helpMenu = menuBar->addMenu("&Help"); helpMenu->addAction("&Welcome",this, SLOT(onIntro())); helpMenu->addAction("&Open Help Perspective", this, SLOT(onHelpOpenHelpPerspective())); helpMenu->addAction("&Context Help",this, SLOT(onHelp()), QKeySequence("F1")); helpMenu->addAction("&About",this, SLOT(onAbout())); // ===================================================== QStatusBar* qStatusBar = new QStatusBar(); //creating a QmitkStatusBar for Output on the QStatusBar and connecting it with the MainStatusBar QmitkStatusBar *statusBar = new QmitkStatusBar(qStatusBar); //disabling the SizeGrip in the lower right corner statusBar->SetSizeGripEnabled(false); QmitkProgressBar *progBar = new QmitkProgressBar(); qStatusBar->addPermanentWidget(progBar, 0); progBar->hide(); // progBar->AddStepsToDo(2); // progBar->Progress(1); mainWindow->setStatusBar(qStatusBar); QmitkMemoryUsageIndicatorView* memoryIndicator = new QmitkMemoryUsageIndicatorView(); qStatusBar->addPermanentWidget(memoryIndicator, 0); } void QmitkExtWorkbenchWindowAdvisor::PreWindowOpen() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); // show the shortcut bar and progress indicator, which are hidden by // default //configurer->SetShowPerspectiveBar(true); //configurer->SetShowFastViewBars(true); //configurer->SetShowProgressIndicator(true); // // add the drag and drop support for the editor area // configurer.addEditorAreaTransfer(EditorInputTransfer.getInstance()); // configurer.addEditorAreaTransfer(ResourceTransfer.getInstance()); // configurer.addEditorAreaTransfer(FileTransfer.getInstance()); // configurer.addEditorAreaTransfer(MarkerTransfer.getInstance()); // configurer.configureEditorAreaDropListener(new EditorAreaDropAdapter( // configurer.getWindow())); this->HookTitleUpdateListeners(configurer); menuPerspectiveListener = new PerspectiveListenerForMenu(this); configurer->GetWindow()->AddPerspectiveListener(menuPerspectiveListener); configurer->AddEditorAreaTransfer(QStringList("text/uri-list")); configurer->ConfigureEditorAreaDropListener(dropTargetListener); } void QmitkExtWorkbenchWindowAdvisor::PostWindowOpen() { // Force Rendering Window Creation on startup. berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); ctkServiceReference serviceRef = context->getServiceReference(); if (serviceRef) { mitk::IDataStorageService *dsService = context->getService(serviceRef); if (dsService) { mitk::IDataStorageReference::Pointer dsRef = dsService->GetDataStorage(); mitk::DataStorageEditorInput::Pointer dsInput(new mitk::DataStorageEditorInput(dsRef)); mitk::WorkbenchUtil::OpenEditor(configurer->GetWindow()->GetActivePage(),dsInput); } } } void QmitkExtWorkbenchWindowAdvisor::onIntro() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onIntro(); } void QmitkExtWorkbenchWindowAdvisor::onHelp() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onHelp(); } void QmitkExtWorkbenchWindowAdvisor::onHelpOpenHelpPerspective() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onHelpOpenHelpPerspective(); } void QmitkExtWorkbenchWindowAdvisor::onAbout() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onAbout(); } //-------------------------------------------------------------------------------- // Ugly hack from here on. Feel free to delete when command framework // and undo buttons are done. //-------------------------------------------------------------------------------- QmitkExtWorkbenchWindowAdvisorHack::QmitkExtWorkbenchWindowAdvisorHack() : QObject() { } QmitkExtWorkbenchWindowAdvisorHack::~QmitkExtWorkbenchWindowAdvisorHack() { } void QmitkExtWorkbenchWindowAdvisorHack::onUndo() { mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel(); if (model) { if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast( model )) { mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetUndoDescriptions(); if (descriptions.size() >= 1) { MITK_INFO << "Undo " << descriptions.front().second; } } model->Undo(); } else { MITK_ERROR << "No undo model instantiated"; } } void QmitkExtWorkbenchWindowAdvisorHack::onRedo() { mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel(); if (model) { if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast( model )) { mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetRedoDescriptions(); if (descriptions.size() >= 1) { MITK_INFO << "Redo " << descriptions.front().second; } } model->Redo(); } else { MITK_ERROR << "No undo model instantiated"; } } void QmitkExtWorkbenchWindowAdvisorHack::onImageNavigator() { // get ImageNavigatorView berry::IViewPart::Pointer imageNavigatorView = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.imagenavigator"); if (imageNavigatorView) { bool isImageNavigatorVisible = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->IsPartVisible(imageNavigatorView); if (isImageNavigatorVisible) { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->HideView(imageNavigatorView); return; } } berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ShowView("org.mitk.views.imagenavigator"); //berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkExtWorkbenchWindowAdvisorHack::onEditPreferences() { QmitkPreferencesDialog _PreferencesDialog(QApplication::activeWindow()); _PreferencesDialog.exec(); } void QmitkExtWorkbenchWindowAdvisorHack::onQuit() { berry::PlatformUI::GetWorkbench()->Close(); } void QmitkExtWorkbenchWindowAdvisorHack::onResetPerspective() { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkExtWorkbenchWindowAdvisorHack::onClosePerspective() { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); page->ClosePerspective(page->GetPerspective(), true, true); } void QmitkExtWorkbenchWindowAdvisorHack::onNewWindow() { berry::PlatformUI::GetWorkbench()->OpenWorkbenchWindow(0); } void QmitkExtWorkbenchWindowAdvisorHack::onIntro() { bool hasIntro = berry::PlatformUI::GetWorkbench()->GetIntroManager()->HasIntro(); if (!hasIntro) { QRegExp reg("(.*)(\\n)*"); QRegExp reg2("(\\n)*(.*)"); QFile file(":/org.mitk.gui.qt.ext/index.html"); - file.open(QIODevice::ReadOnly | QIODevice::Text); // Als Text-Datei nur zum Lesen öffnen + file.open(QIODevice::ReadOnly | QIODevice::Text); //text file only for reading QString text = QString(file.readAll()); file.close(); QString title = text; title.replace(reg, ""); title.replace(reg2, ""); std::cout << title.toStdString() << std::endl; QMessageBox::information(NULL, title, text, "Close"); } else { berry::PlatformUI::GetWorkbench()->GetIntroManager()->ShowIntro( berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), false); } } void QmitkExtWorkbenchWindowAdvisorHack::onHelp() { ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); if (context == 0) { MITK_WARN << "Plugin context not set, unable to open context help"; return; } // Check if the org.blueberry.ui.qt.help plug-in is installed and started QList > plugins = context->getPlugins(); foreach(QSharedPointer p, plugins) { if (p->getSymbolicName() == "org.blueberry.ui.qt.help") { if (p->getState() != ctkPlugin::ACTIVE) { // try to activate the plug-in explicitly try { p->start(ctkPlugin::START_TRANSIENT); } catch (const ctkPluginException& pe) { MITK_ERROR << "Activating org.blueberry.ui.qt.help failed: " << pe.what(); return; } } } } ctkServiceReference eventAdminRef = context->getServiceReference(); ctkEventAdmin* eventAdmin = 0; if (eventAdminRef) { eventAdmin = context->getService(eventAdminRef); } if (eventAdmin == 0) { MITK_WARN << "ctkEventAdmin service not found. Unable to open context help"; } else { ctkEvent ev("org/blueberry/ui/help/CONTEXTHELP_REQUESTED"); eventAdmin->postEvent(ev); } } void QmitkExtWorkbenchWindowAdvisorHack::onHelpOpenHelpPerspective() { berry::PlatformUI::GetWorkbench()->ShowPerspective("org.blueberry.perspectives.help", berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()); } void QmitkExtWorkbenchWindowAdvisorHack::onAbout() { QmitkAboutDialog* aboutDialog = new QmitkAboutDialog(QApplication::activeWindow(),NULL); aboutDialog->open(); } void QmitkExtWorkbenchWindowAdvisor::HookTitleUpdateListeners( berry::IWorkbenchWindowConfigurer::Pointer configurer) { // hook up the listeners to update the window title titlePartListener = new PartListenerForTitle(this); titlePerspectiveListener = new PerspectiveListenerForTitle(this); editorPropertyListener = new berry::PropertyChangeIntAdapter< QmitkExtWorkbenchWindowAdvisor>(this, &QmitkExtWorkbenchWindowAdvisor::PropertyChange); // configurer.getWindow().addPageListener(new IPageListener() { // public void pageActivated(IWorkbenchPage page) { // updateTitle(false); // } // // public void pageClosed(IWorkbenchPage page) { // updateTitle(false); // } // // public void pageOpened(IWorkbenchPage page) { // // do nothing // } // }); configurer->GetWindow()->AddPerspectiveListener(titlePerspectiveListener); configurer->GetWindow()->GetPartService()->AddPartListener(titlePartListener); } std::string QmitkExtWorkbenchWindowAdvisor::ComputeTitle() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); berry::IWorkbenchPage::Pointer currentPage = configurer->GetWindow()->GetActivePage(); berry::IEditorPart::Pointer activeEditor; if (currentPage) { activeEditor = lastActiveEditor.Lock(); } std::string title; //TODO Product // IProduct product = Platform.getProduct(); // if (product != null) { // title = product.getName(); // } // instead of the product name, we use a custom variable for now title = productName; if(showMitkVersionInfo) { title += std::string(" ") + MITK_VERSION_STRING; } if (showVersionInfo) { // add version informatioin QString versions = QString(" (ITK %1.%2.%3 VTK %4.%5.%6 Qt %7 MITK %8)") .arg(ITK_VERSION_MAJOR).arg(ITK_VERSION_MINOR).arg(ITK_VERSION_PATCH) .arg(VTK_MAJOR_VERSION).arg(VTK_MINOR_VERSION).arg(VTK_BUILD_VERSION) .arg(QT_VERSION_STR) .arg(MITK_VERSION_STRING); title += versions.toStdString(); } if (currentPage) { if (activeEditor) { lastEditorTitle = activeEditor->GetTitleToolTip(); if (!lastEditorTitle.empty()) title = lastEditorTitle + " - " + title; } berry::IPerspectiveDescriptor::Pointer persp = currentPage->GetPerspective(); std::string label = ""; if (persp) { label = persp->GetLabel(); } berry::IAdaptable* input = currentPage->GetInput(); if (input && input != wbAdvisor->GetDefaultPageInput()) { label = currentPage->GetLabel(); } if (!label.empty()) { title = label + " - " + title; } } title += " (Not for use in diagnosis or treatment of patients)"; return title; } void QmitkExtWorkbenchWindowAdvisor::RecomputeTitle() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); std::string oldTitle = configurer->GetTitle(); std::string newTitle = ComputeTitle(); if (newTitle != oldTitle) { configurer->SetTitle(newTitle); } } void QmitkExtWorkbenchWindowAdvisor::UpdateTitle(bool editorHidden) { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); berry::IWorkbenchWindow::Pointer window = configurer->GetWindow(); berry::IEditorPart::Pointer activeEditor; berry::IWorkbenchPage::Pointer currentPage = window->GetActivePage(); berry::IPerspectiveDescriptor::Pointer persp; berry::IAdaptable* input = 0; if (currentPage) { activeEditor = currentPage->GetActiveEditor(); persp = currentPage->GetPerspective(); input = currentPage->GetInput(); } if (editorHidden) { activeEditor = 0; } // Nothing to do if the editor hasn't changed if (activeEditor == lastActiveEditor.Lock() && currentPage == lastActivePage.Lock() && persp == lastPerspective.Lock() && input == lastInput) { return; } if (!lastActiveEditor.Expired()) { lastActiveEditor.Lock()->RemovePropertyListener(editorPropertyListener); } lastActiveEditor = activeEditor; lastActivePage = currentPage; lastPerspective = persp; lastInput = input; if (activeEditor) { activeEditor->AddPropertyListener(editorPropertyListener); } RecomputeTitle(); } void QmitkExtWorkbenchWindowAdvisor::PropertyChange(berry::Object::Pointer /*source*/, int propId) { if (propId == berry::IWorkbenchPartConstants::PROP_TITLE) { if (!lastActiveEditor.Expired()) { std::string newTitle = lastActiveEditor.Lock()->GetPartName(); if (lastEditorTitle != newTitle) { RecomputeTitle(); } } } } void QmitkExtWorkbenchWindowAdvisor::SetPerspectiveExcludeList(std::vector v) { this->perspectiveExcludeList = v; } std::vector QmitkExtWorkbenchWindowAdvisor::GetPerspectiveExcludeList() { return this->perspectiveExcludeList; } void QmitkExtWorkbenchWindowAdvisor::SetViewExcludeList(std::vector v) { this->viewExcludeList = v; } std::vector QmitkExtWorkbenchWindowAdvisor::GetViewExcludeList() { return this->viewExcludeList; } void QmitkExtWorkbenchWindowAdvisor::PostWindowClose() { berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); QMainWindow* mainWindow = static_cast (window->GetShell()->GetControl()); QSettings settings(GetQSettingsFile(), QSettings::IniFormat); settings.setValue("ToolbarPosition", mainWindow->saveState()); } QString QmitkExtWorkbenchWindowAdvisor::GetQSettingsFile() const { QFileInfo settingsInfo = QmitkCommonExtPlugin::getContext()->getDataFile(QT_SETTINGS_FILENAME); return settingsInfo.canonicalFilePath(); } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreatePolygonModelAction.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreatePolygonModelAction.cpp index ca868fc0ac..3aa73a17b5 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreatePolygonModelAction.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreatePolygonModelAction.cpp @@ -1,171 +1,171 @@ /*=================================================================== 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. ===================================================================*/ #include "QmitkCreatePolygonModelAction.h" // MITK #include #include #include #include #include #include #include // Blueberry #include #include #include using namespace berry; using namespace mitk; using namespace std; QmitkCreatePolygonModelAction::QmitkCreatePolygonModelAction() { } QmitkCreatePolygonModelAction::~QmitkCreatePolygonModelAction() { } void QmitkCreatePolygonModelAction::Run(const QList &selectedNodes) { DataNode::Pointer selectedNode = selectedNodes[0]; Image::Pointer image = dynamic_cast(selectedNode->GetData()); if (image.IsNull()) return; try { if (!m_IsSmoothed) { ShowSegmentationAsSurface::Pointer surfaceFilter = ShowSegmentationAsSurface::New(); itk::SimpleMemberCommand::Pointer successCommand = itk::SimpleMemberCommand::New(); successCommand->SetCallbackFunction(this, &QmitkCreatePolygonModelAction::OnSurfaceCalculationDone); surfaceFilter->AddObserver(ResultAvailable(), successCommand); itk::SimpleMemberCommand::Pointer errorCommand = itk::SimpleMemberCommand::New(); errorCommand->SetCallbackFunction(this, &QmitkCreatePolygonModelAction::OnSurfaceCalculationDone); surfaceFilter->AddObserver(ProcessingError(), errorCommand); surfaceFilter->SetDataStorage(*m_DataStorage); surfaceFilter->SetPointerParameter("Input", image); surfaceFilter->SetPointerParameter("Group node", selectedNode); surfaceFilter->SetParameter("Show result", true); surfaceFilter->SetParameter("Sync visibility", false); surfaceFilter->SetParameter("Smooth", false); surfaceFilter->SetParameter("Apply median", false); surfaceFilter->SetParameter("Median kernel size", 3u); surfaceFilter->SetParameter("Gaussian SD", 1.5f); surfaceFilter->SetParameter("Decimate mesh", m_IsDecimated); surfaceFilter->SetParameter("Decimation rate", 0.8f); StatusBar::GetInstance()->DisplayText("Surface creation started in background..."); surfaceFilter->StartAlgorithm(); } else { ShowSegmentationAsSmoothedSurface::Pointer surfaceFilter = ShowSegmentationAsSmoothedSurface::New(); itk::SimpleMemberCommand::Pointer successCommand = itk::SimpleMemberCommand::New(); successCommand->SetCallbackFunction(this, &QmitkCreatePolygonModelAction::OnSurfaceCalculationDone); surfaceFilter->AddObserver(mitk::ResultAvailable(), successCommand); itk::SimpleMemberCommand::Pointer errorCommand = itk::SimpleMemberCommand::New(); errorCommand->SetCallbackFunction(this, &QmitkCreatePolygonModelAction::OnSurfaceCalculationDone); surfaceFilter->AddObserver(mitk::ProcessingError(), errorCommand); surfaceFilter->SetDataStorage(*m_DataStorage); surfaceFilter->SetPointerParameter("Input", image); surfaceFilter->SetPointerParameter("Group node", selectedNode); berry::IWorkbenchPart::Pointer activePart = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->GetActivePart(); mitk::IRenderWindowPart* renderPart = dynamic_cast(activePart.GetPointer()); mitk::SliceNavigationController* timeNavController = 0; if (renderPart != 0) { timeNavController = renderPart->GetRenderingManager()->GetTimeNavigationController(); } int timeNr = timeNavController != 0 ? timeNavController->GetTime()->GetPos() : 0; surfaceFilter->SetParameter("TimeNr", timeNr); IPreferencesService::Pointer prefService = Platform::GetServiceRegistry().GetServiceById(IPreferencesService::ID); IPreferences::Pointer segPref = prefService->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); bool smoothingHint = segPref->GetBool("smoothing hint", true); - float smoothing = (float)segPref->GetDouble("smoothing value", 1.0); - float decimation = (float)segPref->GetDouble("decimation rate", 0.5); - float closing = (float)segPref->GetDouble("closing ratio", 0.0); + ScalarType smoothing = segPref->GetDouble("smoothing value", 1.0); + ScalarType decimation = segPref->GetDouble("decimation rate", 0.5); + ScalarType closing = segPref->GetDouble("closing ratio", 0.0); if (smoothingHint) { smoothing = 0.0; Vector3D spacing = image->GetGeometry()->GetSpacing(); for (Vector3D::Iterator iter = spacing.Begin(); iter != spacing.End(); ++iter) smoothing = max(smoothing, *iter); } surfaceFilter->SetParameter("Smoothing", smoothing); surfaceFilter->SetParameter("Decimation", decimation); surfaceFilter->SetParameter("Closing", closing); ProgressBar::GetInstance()->AddStepsToDo(8); StatusBar::GetInstance()->DisplayText("Smoothed surface creation started in background..."); try { surfaceFilter->StartAlgorithm(); } catch (...) { MITK_ERROR<<"Error creating smoothed polygon model: Not enough memory!"; } } } catch(...) { MITK_ERROR << "Surface creation failed!"; } } void QmitkCreatePolygonModelAction::OnSurfaceCalculationDone() { StatusBar::GetInstance()->Clear(); } void QmitkCreatePolygonModelAction::SetDataStorage(DataStorage *dataStorage) { m_DataStorage = dataStorage; } void QmitkCreatePolygonModelAction::SetSmoothed(bool smoothed) { m_IsSmoothed = smoothed; } void QmitkCreatePolygonModelAction::SetDecimated(bool decimated) { m_IsDecimated = decimated; } void QmitkCreatePolygonModelAction::SetFunctionality(QtViewPart *) { }