diff --git a/Core/Code/Controllers/mitkRenderingManager.cpp b/Core/Code/Controllers/mitkRenderingManager.cpp index 8c39fa5615..a9a8b32326 100644 --- a/Core/Code/Controllers/mitkRenderingManager.cpp +++ b/Core/Code/Controllers/mitkRenderingManager.cpp @@ -1,1031 +1,1031 @@ /*=================================================================== 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 "mitkRenderingManager.h" #include "mitkRenderingManagerFactory.h" #include "mitkBaseRenderer.h" #include "mitkGlobalInteraction.h" #include #include -#include "mitkVector.h" +#include "mitkTypes.h" #include #include #include #include namespace mitk { RenderingManager::Pointer RenderingManager::s_Instance = 0; RenderingManagerFactory *RenderingManager::s_RenderingManagerFactory = 0; RenderingManager ::RenderingManager() : m_UpdatePending( false ), m_MaxLOD( 1 ), m_LODIncreaseBlocked( false ), m_LODAbortMechanismEnabled( false ), m_ClippingPlaneEnabled( false ), m_TimeNavigationController( SliceNavigationController::New("dummy") ), m_DataStorage( NULL ), m_ConstrainedPaddingZooming ( true ) { m_ShadingEnabled.assign( 3, false ); m_ShadingValues.assign( 4, 0.0 ); m_GlobalInteraction = mitk::GlobalInteraction::GetInstance(); InitializePropertyList(); } RenderingManager ::~RenderingManager() { // Decrease reference counts of all registered vtkRenderWindows for // proper destruction RenderWindowVector::iterator it; for ( it = m_AllRenderWindows.begin(); it != m_AllRenderWindows.end(); ++it ) { (*it)->UnRegister( NULL ); RenderWindowCallbacksList::iterator callbacks_it = this->m_RenderWindowCallbacksList.find(*it); if (callbacks_it != this->m_RenderWindowCallbacksList.end()) { (*it)->RemoveObserver(callbacks_it->second.commands[0u]); (*it)->RemoveObserver(callbacks_it->second.commands[1u]); (*it)->RemoveObserver(callbacks_it->second.commands[2u]); } } } void RenderingManager ::SetFactory( RenderingManagerFactory *factory ) { s_RenderingManagerFactory = factory; } const RenderingManagerFactory * RenderingManager ::GetFactory() { return s_RenderingManagerFactory; } bool RenderingManager ::HasFactory() { if ( RenderingManager::s_RenderingManagerFactory ) { return true; } else { return false; } } RenderingManager::Pointer RenderingManager ::New() { const RenderingManagerFactory* factory = GetFactory(); if(factory == NULL) return NULL; return factory->CreateRenderingManager(); } RenderingManager * RenderingManager ::GetInstance() { if ( !RenderingManager::s_Instance ) { if ( s_RenderingManagerFactory ) { s_Instance = s_RenderingManagerFactory->CreateRenderingManager(); } } return s_Instance; } bool RenderingManager ::IsInstantiated() { if ( RenderingManager::s_Instance ) return true; else return false; } void RenderingManager ::AddRenderWindow( vtkRenderWindow *renderWindow ) { if ( renderWindow && (m_RenderWindowList.find( renderWindow ) == m_RenderWindowList.end()) ) { m_RenderWindowList[renderWindow] = RENDERING_INACTIVE; m_AllRenderWindows.push_back( renderWindow ); if ( m_DataStorage.IsNotNull() ) mitk::BaseRenderer::GetInstance( renderWindow )->SetDataStorage( m_DataStorage.GetPointer() ); // Register vtkRenderWindow instance renderWindow->Register( NULL ); // Add callbacks for rendering abort mechanism //BaseRenderer *renderer = BaseRenderer::GetInstance( renderWindow ); vtkCallbackCommand *startCallbackCommand = vtkCallbackCommand::New(); startCallbackCommand->SetCallback( RenderingManager::RenderingStartCallback ); renderWindow->AddObserver( vtkCommand::StartEvent, startCallbackCommand ); vtkCallbackCommand *progressCallbackCommand = vtkCallbackCommand::New(); progressCallbackCommand->SetCallback( RenderingManager::RenderingProgressCallback ); renderWindow->AddObserver( vtkCommand::AbortCheckEvent, progressCallbackCommand ); vtkCallbackCommand *endCallbackCommand = vtkCallbackCommand::New(); endCallbackCommand->SetCallback( RenderingManager::RenderingEndCallback ); renderWindow->AddObserver( vtkCommand::EndEvent, endCallbackCommand ); RenderWindowCallbacks callbacks; callbacks.commands[0u] = startCallbackCommand; callbacks.commands[1u] = progressCallbackCommand; callbacks.commands[2u] = endCallbackCommand; this->m_RenderWindowCallbacksList[renderWindow] = callbacks; //Delete vtk variables correctly startCallbackCommand->Delete(); progressCallbackCommand->Delete(); endCallbackCommand->Delete(); } } void RenderingManager ::RemoveRenderWindow( vtkRenderWindow *renderWindow ) { if (m_RenderWindowList.erase( renderWindow )) { RenderWindowCallbacksList::iterator callbacks_it = this->m_RenderWindowCallbacksList.find(renderWindow); if(callbacks_it != this->m_RenderWindowCallbacksList.end()) { renderWindow->RemoveObserver(callbacks_it->second.commands[0u]); renderWindow->RemoveObserver(callbacks_it->second.commands[1u]); renderWindow->RemoveObserver(callbacks_it->second.commands[2u]); this->m_RenderWindowCallbacksList.erase(callbacks_it); } RenderWindowVector::iterator rw_it = std::find( m_AllRenderWindows.begin(), m_AllRenderWindows.end(), renderWindow ); if(rw_it != m_AllRenderWindows.end()) { // Decrease reference count for proper destruction (*rw_it)->UnRegister(NULL); m_AllRenderWindows.erase( rw_it ); } } } const RenderingManager::RenderWindowVector& RenderingManager ::GetAllRegisteredRenderWindows() { return m_AllRenderWindows; } void RenderingManager ::RequestUpdate( vtkRenderWindow *renderWindow ) { // If the renderWindow is not valid, we do not want to inadvertantly create // an entry in the m_RenderWindowList map. It is possible if the user is // regularly calling AddRenderer and RemoveRenderer for a rendering update // to come into this method with a renderWindow pointer that is valid in the // sense that the window does exist within the application, but that // renderWindow has been temporarily removed from this RenderingManager for // performance reasons. if (m_RenderWindowList.find( renderWindow ) == m_RenderWindowList.end()) { return; } m_RenderWindowList[renderWindow] = RENDERING_REQUESTED; if ( !m_UpdatePending ) { m_UpdatePending = true; this->GenerateRenderingRequestEvent(); } } void RenderingManager ::ForceImmediateUpdate( vtkRenderWindow *renderWindow ) { // If the renderWindow is not valid, we do not want to inadvertantly create // an entry in the m_RenderWindowList map. It is possible if the user is // regularly calling AddRenderer and RemoveRenderer for a rendering update // to come into this method with a renderWindow pointer that is valid in the // sense that the window does exist within the application, but that // renderWindow has been temporarily removed from this RenderingManager for // performance reasons. if (m_RenderWindowList.find( renderWindow ) == m_RenderWindowList.end()) { return; } // Erase potentially pending requests for this window m_RenderWindowList[renderWindow] = RENDERING_INACTIVE; m_UpdatePending = false; // Immediately repaint this window (implementation platform specific) // If the size is 0 it crahses int *size = renderWindow->GetSize(); if ( 0 != size[0] && 0 != size[1] ) { //prepare the camera etc. before rendering //Note: this is a very important step which should be called before the VTK render! //If you modify the camera anywhere else or after the render call, the scene cannot be seen. mitk::VtkPropRenderer *vPR = dynamic_cast(mitk::BaseRenderer::GetInstance( renderWindow )); if(vPR) vPR->PrepareRender(); // Execute rendering renderWindow->Render(); } } void RenderingManager ::RequestUpdateAll( RequestType type ) { RenderWindowList::iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { int id = BaseRenderer::GetInstance(it->first)->GetMapperID(); if ( (type == REQUEST_UPDATE_ALL) || ((type == REQUEST_UPDATE_2DWINDOWS) && (id == 1)) || ((type == REQUEST_UPDATE_3DWINDOWS) && (id == 2)) ) { this->RequestUpdate( it->first ); } } } void RenderingManager ::ForceImmediateUpdateAll( RequestType type ) { RenderWindowList::iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { int id = BaseRenderer::GetInstance(it->first)->GetMapperID(); if ( (type == REQUEST_UPDATE_ALL) || ((type == REQUEST_UPDATE_2DWINDOWS) && (id == 1)) || ((type == REQUEST_UPDATE_3DWINDOWS) && (id == 2)) ) { // Immediately repaint this window (implementation platform specific) // If the size is 0, it crashes this->ForceImmediateUpdate(it->first); // int *size = it->first->GetSize(); // if ( 0 != size[0] && 0 != size[1] ) // { // //prepare the camera before rendering // //Note: this is a very important step which should be called before the VTK render! // //If you modify the camera anywhere else or after the render call, the scene cannot be seen. // mitk::VtkPropRenderer *vPR = // dynamic_cast(mitk::BaseRenderer::GetInstance( it->first )); // if(vPR) // vPR->PrepareRender(); // // Execute rendering // it->first->Render(); // } // it->second = RENDERING_INACTIVE; } } //m_UpdatePending = false; } //bool RenderingManager::InitializeViews( const mitk::DataStorage * storage, const DataNode* node = NULL, RequestType type, bool preserveRoughOrientationInWorldSpace ) //{ // mitk::Geometry3D::Pointer geometry; // if ( storage != NULL ) // { // geometry = storage->ComputeVisibleBoundingGeometry3D(node, "visible", NULL, "includeInBoundingBox" ); // // if ( geometry.IsNotNull() ) // { // // let's see if we have data with a limited live-span ... // mitk::TimeBounds timebounds = geometry->GetTimeBounds(); // if ( timebounds[1] < mitk::ScalarTypeNumericTraits::max() ) // { // mitk::ScalarType duration = timebounds[1]-timebounds[0]; // // mitk::TimeSlicedGeometry::Pointer timegeometry = // mitk::TimeSlicedGeometry::New(); // timegeometry->InitializeEvenlyTimed( // geometry, (unsigned int) duration ); // timegeometry->SetTimeBounds( timebounds ); // // timebounds[1] = timebounds[0] + 1.0; // geometry->SetTimeBounds( timebounds ); // // geometry = timegeometry; // } // } // } // // // Use geometry for initialization // return this->InitializeViews( geometry.GetPointer(), type ); //} bool RenderingManager ::InitializeViews( const Geometry3D * dataGeometry, RequestType type, bool preserveRoughOrientationInWorldSpace ) { MITK_DEBUG << "initializing views"; bool boundingBoxInitialized = false; Geometry3D::ConstPointer geometry = dataGeometry; if (dataGeometry && preserveRoughOrientationInWorldSpace) { // clone the input geometry Geometry3D::Pointer modifiedGeometry = dynamic_cast( dataGeometry->Clone().GetPointer() ); assert(modifiedGeometry.IsNotNull()); // construct an affine transform from it AffineGeometryFrame3D::TransformType::Pointer transform = AffineGeometryFrame3D::TransformType::New(); assert( modifiedGeometry->GetIndexToWorldTransform() ); transform->SetMatrix( modifiedGeometry->GetIndexToWorldTransform()->GetMatrix() ); transform->SetOffset( modifiedGeometry->GetIndexToWorldTransform()->GetOffset() ); // get transform matrix AffineGeometryFrame3D::TransformType::MatrixType::InternalMatrixType& oldMatrix = const_cast< AffineGeometryFrame3D::TransformType::MatrixType::InternalMatrixType& > ( transform->GetMatrix().GetVnlMatrix() ); AffineGeometryFrame3D::TransformType::MatrixType::InternalMatrixType newMatrix(oldMatrix); // get offset and bound Vector3D offset = modifiedGeometry->GetIndexToWorldTransform()->GetOffset(); Geometry3D::BoundsArrayType oldBounds = modifiedGeometry->GetBounds(); Geometry3D::BoundsArrayType newBounds = modifiedGeometry->GetBounds(); // get rid of rotation other than pi/2 degree for ( unsigned int i = 0; i < 3; ++i ) { // i-th column of the direction matrix Vector3D currentVector; currentVector[0] = oldMatrix(0,i); currentVector[1] = oldMatrix(1,i); currentVector[2] = oldMatrix(2,i); // matchingRow will store the row that holds the biggest // value in the column unsigned int matchingRow = 0; // maximum value in the column float max = std::numeric_limits::min(); // sign of the maximum value (-1 or 1) int sign = 1; // iterate through the column vector for (unsigned int dim = 0; dim < 3; ++dim) { if ( fabs(currentVector[dim]) > max ) { matchingRow = dim; max = fabs(currentVector[dim]); if(currentVector[dim]<0) sign = -1; else sign = 1; } } // in case we found a negative maximum, // we negate the column and adjust the offset // (in order to run through the dimension in the opposite direction) if(sign == -1) { currentVector *= sign; offset += modifiedGeometry->GetAxisVector(i); } // matchingRow is now used as column index to place currentVector // correctly in the new matrix vnl_vector newMatrixColumn(3); newMatrixColumn[0] = currentVector[0]; newMatrixColumn[1] = currentVector[1]; newMatrixColumn[2] = currentVector[2]; newMatrix.set_column( matchingRow, newMatrixColumn ); // if a column is moved, we also have to adjust the bounding // box accordingly, this is done here newBounds[2*matchingRow ] = oldBounds[2*i ]; newBounds[2*matchingRow+1] = oldBounds[2*i+1]; } // set the newly calculated bounds array modifiedGeometry->SetBounds(newBounds); // set new offset and direction matrix AffineGeometryFrame3D::TransformType::MatrixType newMatrixITK( newMatrix ); transform->SetMatrix( newMatrixITK ); transform->SetOffset( offset ); modifiedGeometry->SetIndexToWorldTransform( transform ); geometry = modifiedGeometry; } int warningLevel = vtkObject::GetGlobalWarningDisplay(); vtkObject::GlobalWarningDisplayOff(); if ( (geometry.IsNotNull() ) && (const_cast< mitk::BoundingBox * >( geometry->GetBoundingBox())->GetDiagonalLength2() > mitk::eps) ) { boundingBoxInitialized = true; } if (geometry.IsNotNull() ) {// make sure bounding box has an extent bigger than zero in any direction // clone the input geometry Geometry3D::Pointer modifiedGeometry = dynamic_cast( dataGeometry->Clone().GetPointer() ); assert(modifiedGeometry.IsNotNull()); Geometry3D::BoundsArrayType newBounds = modifiedGeometry->GetBounds(); for( unsigned int dimension = 0; ( 2 * dimension ) < newBounds.Size() ; dimension++ ) { //check for equality but for an epsilon if( Equal( newBounds[ 2 * dimension ], newBounds[ 2 * dimension + 1 ] ) ) { newBounds[ 2 * dimension + 1 ] += 1; } } // set the newly calculated bounds array modifiedGeometry->SetBounds(newBounds); geometry = modifiedGeometry; } RenderWindowList::iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { mitk::BaseRenderer *baseRenderer = mitk::BaseRenderer::GetInstance( it->first ); baseRenderer->GetDisplayGeometry()->SetConstrainZoomingAndPanning(m_ConstrainedPaddingZooming); int id = baseRenderer->GetMapperID(); if ( ((type == REQUEST_UPDATE_ALL) || ((type == REQUEST_UPDATE_2DWINDOWS) && (id == 1)) || ((type == REQUEST_UPDATE_3DWINDOWS) && (id == 2))) ) { this->InternalViewInitialization( baseRenderer, geometry, boundingBoxInitialized, id ); } } if ( boundingBoxInitialized ) { m_TimeNavigationController->SetInputWorldGeometry( geometry ); } m_TimeNavigationController->Update(); this->RequestUpdateAll( type ); vtkObject::SetGlobalWarningDisplay( warningLevel ); // Inform listeners that views have been initialized this->InvokeEvent( mitk::RenderingManagerViewsInitializedEvent() ); return boundingBoxInitialized; } bool RenderingManager ::InitializeViews( RequestType type ) { RenderWindowList::iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { mitk::BaseRenderer *baseRenderer = mitk::BaseRenderer::GetInstance( it->first ); int id = baseRenderer->GetMapperID(); if ( (type == REQUEST_UPDATE_ALL) || ((type == REQUEST_UPDATE_2DWINDOWS) && (id == 1)) || ((type == REQUEST_UPDATE_3DWINDOWS) && (id == 2)) ) { mitk::SliceNavigationController *nc = baseRenderer->GetSliceNavigationController(); // Re-initialize view direction nc->SetViewDirectionToDefault(); // Update the SNC nc->Update(); } } this->RequestUpdateAll( type ); return true; } //bool RenderingManager::InitializeView( vtkRenderWindow * renderWindow, const DataStorage* ds, const DataNode node = NULL, bool initializeGlobalTimeSNC ) //{ // mitk::Geometry3D::Pointer geometry; // if ( ds != NULL ) // { // geometry = ds->ComputeVisibleBoundingGeometry3D(node, NULL, "includeInBoundingBox" ); // // if ( geometry.IsNotNull() ) // { // // let's see if we have data with a limited live-span ... // mitk::TimeBounds timebounds = geometry->GetTimeBounds(); // if ( timebounds[1] < mitk::ScalarTypeNumericTraits::max() ) // { // mitk::ScalarType duration = timebounds[1]-timebounds[0]; // // mitk::TimeSlicedGeometry::Pointer timegeometry = // mitk::TimeSlicedGeometry::New(); // timegeometry->InitializeEvenlyTimed( // geometry, (unsigned int) duration ); // timegeometry->SetTimeBounds( timebounds ); // // timebounds[1] = timebounds[0] + 1.0; // geometry->SetTimeBounds( timebounds ); // // geometry = timegeometry; // } // } // } // // // Use geometry for initialization // return this->InitializeView( renderWindow, // geometry.GetPointer(), initializeGlobalTimeSNC ); //} bool RenderingManager::InitializeView( vtkRenderWindow * renderWindow, const Geometry3D * geometry, bool initializeGlobalTimeSNC ) { bool boundingBoxInitialized = false; int warningLevel = vtkObject::GetGlobalWarningDisplay(); vtkObject::GlobalWarningDisplayOff(); if ( (geometry != NULL ) && (const_cast< mitk::BoundingBox * >( geometry->GetBoundingBox())->GetDiagonalLength2() > mitk::eps) ) { boundingBoxInitialized = true; } mitk::BaseRenderer *baseRenderer = mitk::BaseRenderer::GetInstance( renderWindow ); int id = baseRenderer->GetMapperID(); this->InternalViewInitialization( baseRenderer, geometry, boundingBoxInitialized, id ); if ( boundingBoxInitialized && initializeGlobalTimeSNC ) { m_TimeNavigationController->SetInputWorldGeometry( geometry ); } m_TimeNavigationController->Update(); this->RequestUpdate( renderWindow ); vtkObject::SetGlobalWarningDisplay( warningLevel ); return boundingBoxInitialized; } bool RenderingManager::InitializeView( vtkRenderWindow * renderWindow ) { mitk::BaseRenderer *baseRenderer = mitk::BaseRenderer::GetInstance( renderWindow ); mitk::SliceNavigationController *nc = baseRenderer->GetSliceNavigationController(); // Re-initialize view direction nc->SetViewDirectionToDefault(); // Update the SNC nc->Update(); this->RequestUpdate( renderWindow ); return true; } void RenderingManager::InternalViewInitialization(mitk::BaseRenderer *baseRenderer, const mitk::Geometry3D *geometry, bool boundingBoxInitialized, int mapperID ) { mitk::SliceNavigationController *nc = baseRenderer->GetSliceNavigationController(); // Re-initialize view direction nc->SetViewDirectionToDefault(); if ( boundingBoxInitialized ) { // Set geometry for NC nc->SetInputWorldGeometry( geometry ); nc->Update(); if ( mapperID == 1 ) { // For 2D SNCs, steppers are set so that the cross is centered // in the image nc->GetSlice()->SetPos( nc->GetSlice()->GetSteps() / 2 ); } // Fit the render window DisplayGeometry baseRenderer->GetDisplayGeometry()->Fit(); baseRenderer->GetCameraController()->SetViewToAnterior(); } else { nc->Update(); } } const SliceNavigationController* RenderingManager::GetTimeNavigationController() const { return m_TimeNavigationController.GetPointer(); } SliceNavigationController* RenderingManager::GetTimeNavigationController() { return m_TimeNavigationController.GetPointer(); } void RenderingManager::ExecutePendingRequests() { m_UpdatePending = false; // Satisfy all pending update requests RenderWindowList::iterator it; int i = 0; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it, ++i ) { if ( it->second == RENDERING_REQUESTED ) { this->ForceImmediateUpdate( it->first ); } } } void RenderingManager::RenderingStartCallback( vtkObject *caller, unsigned long , void *, void * ) { vtkRenderWindow *renderWindow = dynamic_cast< vtkRenderWindow * >( caller ); mitk::RenderingManager* renman = mitk::BaseRenderer::GetInstance(renderWindow)->GetRenderingManager(); RenderWindowList &renderWindowList = renman->m_RenderWindowList; if ( renderWindow ) { renderWindowList[renderWindow] = RENDERING_INPROGRESS; } renman->m_UpdatePending = false; } void RenderingManager ::RenderingProgressCallback( vtkObject *caller, unsigned long , void *, void * ) { vtkRenderWindow *renderWindow = dynamic_cast< vtkRenderWindow * >( caller ); mitk::RenderingManager* renman = mitk::BaseRenderer::GetInstance(renderWindow)->GetRenderingManager(); if ( renman->m_LODAbortMechanismEnabled ) { vtkRenderWindow *renderWindow = dynamic_cast< vtkRenderWindow * >( caller ); if ( renderWindow ) { BaseRenderer *renderer = BaseRenderer::GetInstance( renderWindow ); if ( renderer && (renderer->GetNumberOfVisibleLODEnabledMappers() > 0) ) { renman->DoMonitorRendering(); } } } } void RenderingManager ::RenderingEndCallback( vtkObject *caller, unsigned long , void *, void * ) { vtkRenderWindow *renderWindow = dynamic_cast< vtkRenderWindow * >( caller ); mitk::RenderingManager* renman = mitk::BaseRenderer::GetInstance(renderWindow)->GetRenderingManager(); RenderWindowList &renderWindowList = renman->m_RenderWindowList; RendererIntMap &nextLODMap = renman->m_NextLODMap; if ( renderWindow ) { BaseRenderer *renderer = BaseRenderer::GetInstance( renderWindow ); if ( renderer ) { renderWindowList[renderer->GetRenderWindow()] = RENDERING_INACTIVE; // Level-of-Detail handling if ( renderer->GetNumberOfVisibleLODEnabledMappers() > 0 ) { if(nextLODMap[renderer]==0) renman->StartOrResetTimer(); else nextLODMap[renderer] = 0; } } } } bool RenderingManager ::IsRendering() const { RenderWindowList::const_iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { if ( it->second == RENDERING_INPROGRESS ) { return true; } } return false; } void RenderingManager ::AbortRendering() { RenderWindowList::iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { if ( it->second == RENDERING_INPROGRESS ) { it->first->SetAbortRender( true ); m_RenderingAbortedMap[BaseRenderer::GetInstance(it->first)] = true; } } } int RenderingManager ::GetNextLOD( BaseRenderer *renderer ) { if ( renderer != NULL ) { return m_NextLODMap[renderer]; } else { return 0; } } void RenderingManager ::ExecutePendingHighResRenderingRequest() { RenderWindowList::iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { BaseRenderer *renderer = BaseRenderer::GetInstance( it->first ); if(renderer->GetNumberOfVisibleLODEnabledMappers()>0) { if(m_NextLODMap[renderer]==0) { m_NextLODMap[renderer]=1; RequestUpdate( it->first ); } } } } void RenderingManager ::SetMaximumLOD( unsigned int max ) { m_MaxLOD = max; } //enable/disable shading void RenderingManager ::SetShading(bool state, unsigned int lod) { if(lod>m_MaxLOD) { itkWarningMacro(<<"LOD out of range requested: " << lod << " maxLOD: " << m_MaxLOD); return; } m_ShadingEnabled[lod] = state; } bool RenderingManager ::GetShading(unsigned int lod) { if(lod>m_MaxLOD) { itkWarningMacro(<<"LOD out of range requested: " << lod << " maxLOD: " << m_MaxLOD); return false; } return m_ShadingEnabled[lod]; } //enable/disable the clipping plane void RenderingManager ::SetClippingPlaneStatus(bool status) { m_ClippingPlaneEnabled = status; } bool RenderingManager ::GetClippingPlaneStatus() { return m_ClippingPlaneEnabled; } void RenderingManager ::SetShadingValues(float ambient, float diffuse, float specular, float specpower) { m_ShadingValues[0] = ambient; m_ShadingValues[1] = diffuse; m_ShadingValues[2] = specular; m_ShadingValues[3] = specpower; } RenderingManager::FloatVector & RenderingManager ::GetShadingValues() { return m_ShadingValues; } void RenderingManager::SetDepthPeelingEnabled( bool enabled ) { RenderWindowList::iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { mitk::BaseRenderer *baseRenderer = mitk::BaseRenderer::GetInstance( it->first ); baseRenderer->SetDepthPeelingEnabled(enabled); } } void RenderingManager::SetMaxNumberOfPeels( int maxNumber ) { RenderWindowList::iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { mitk::BaseRenderer *baseRenderer = mitk::BaseRenderer::GetInstance( it->first ); baseRenderer->SetMaxNumberOfPeels(maxNumber); } } void RenderingManager::InitializePropertyList() { if (m_PropertyList.IsNull()) { m_PropertyList = PropertyList::New(); } this->SetProperty("coupled-zoom", BoolProperty::New(false)); this->SetProperty("coupled-plane-rotation", BoolProperty::New(false)); this->SetProperty("MIP-slice-rendering", BoolProperty::New(false)); } PropertyList::Pointer RenderingManager::GetPropertyList() const { return m_PropertyList; } BaseProperty* RenderingManager::GetProperty(const char *propertyKey) const { return m_PropertyList->GetProperty(propertyKey); } void RenderingManager::SetProperty(const char *propertyKey, BaseProperty* propertyValue) { m_PropertyList->SetProperty(propertyKey, propertyValue); } void RenderingManager::SetDataStorage( DataStorage* storage ) { if ( storage != NULL ) { m_DataStorage = storage; RenderingManager::RenderWindowVector::iterator iter; for ( iter = m_AllRenderWindows.begin(); iterSetDataStorage( m_DataStorage.GetPointer() ); } } } mitk::DataStorage* RenderingManager::GetDataStorage() { return m_DataStorage; } void RenderingManager::SetGlobalInteraction( mitk::GlobalInteraction* globalInteraction ) { if ( globalInteraction != NULL ) { m_GlobalInteraction = globalInteraction; } } mitk::GlobalInteraction* RenderingManager::GetGlobalInteraction() { return m_GlobalInteraction; } // Create and register generic RenderingManagerFactory. TestingRenderingManagerFactory renderingManagerFactory; } // namespace diff --git a/Core/Code/Controllers/mitkSlicesRotator.h b/Core/Code/Controllers/mitkSlicesRotator.h index 780e78117b..11171926ac 100644 --- a/Core/Code/Controllers/mitkSlicesRotator.h +++ b/Core/Code/Controllers/mitkSlicesRotator.h @@ -1,165 +1,165 @@ /*=================================================================== 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. ===================================================================*/ #ifndef SLICESROTATOR_H_HEADER_INCLUDED_C1C55A2F #define SLICESROTATOR_H_HEADER_INCLUDED_C1C55A2F #include #pragma GCC visibility push(default) #include #pragma GCC visibility pop -#include +#include namespace mitk { /** \brief Coordinates rotation of multiple visible rendering planes (represented as lines in other render windows). \ingroup NavigationControl This class takes care of several SliceNavigationControllers and handles slice selection / slice rotation. It is added as listener to GlobalInteraction by QmitkStdMultiWidget. The SlicesRotator class adds the possibility of slice rotation to the "normal" behaviour of SliceNavigationControllers (which is picking one plane from a stack of planes). This additional class SlicesRotator is needed, because one has to be aware of multiple "visible slices" (selected Geometry2Ds of some SliceNavigationControllers) in order to choose between rotation and slice selection. Such functionality could not be implemented by a single SliceNavigationController. Rotation is achieved by modifying (rotating) the generated TimeSlicedGeometry of the corresponding SliceNavigationControllers. \section mitkSlicesRotator_StandardCase The standard case: three orthogonal views (MPR) With SlicesRotator, the rule to choose between slice rotation and selection is simple: For a mouse down event, count the number of visible planes, which are "near" the cursor. If this number is 2 (one for the window, which currently holds the cursor, one for the intersection line of another visible slice), then initiate rotation, else select slices near the cursor. If the "LinkPlanes" flag is set, the rotation is applied to the planes of all registered SNCs, not only of the one associated with the directly selected plane. In contrast to the situation without the SlicesRotator, the SliceNavigationControllers are now NOT directly registered as listeners to GlobalInteraction. SlicesRotator is registered as a listener and decides whether something should be rotated or whether another slice should be selected. In the latter case, a PositionEvent is just forwarded to the SliceNavigationController. \section mitkSlicesRotator_GeneralizedCase The generalized case: any number of views Above section as well as the original implementation of this class assumes that we have exactly three 2D vies in our scene. This used to be the standard setup of the MITK associated application for a long time. With custom applications based on MITK it is easy to create different situations. One usual use case would be to have one extra render window display the contents of any of the other ones and behave exactly like it (could e.g. be used on a second screen). In this situation the above assumption "we rotate when there are exactly 2 slices close to the cursor" will not hold: since we always have two render windows displaying the exact same slice, the number of 2 is the minimum we get. Whenever the user clicks in one of those windows and the cursor is close to one of the orthogonal planes, we will get a count of 3 or more planes that are "close to the cursor". For the class to behave correctly, we actually need to distinguish three separate cases: 1. the cursor is not close to any orthogonal planes. This should result in slice selection. 2. the cursor is close to just one orthogonal plane OR multiple which are not distinguishable visually. This should result in rotation. 3. the cursor is close to multiple orthogonal planes which are rendered as distinguishable lines on the render window. This is the case when we hit the crosshair-center of the view. In this case, we need to also just select slices. \section mitkSlicesRotator_Solution Deciding between slice selection and rotation The "counting nearby lines in the renderwindow" can also work for the general case described above. Only one details needs to be accounted for: we must not count a line when it is identical to another line. I.e. we just count how many visible lines on the screen are very close to the cursor. When this number is 1, we rotate, otherwise we let the SliceNavigationControllers do their slice selection job. \sa SlicesSwiveller */ class MITK_CORE_EXPORT SlicesRotator : public SlicesCoordinator { public: mitkClassMacro(SlicesRotator, SlicesCoordinator); static Pointer New(); /** \brief New Macro with one parameter for creating this object with static New(..) method. Needs to be the "slices-rotator" pattern of StateMachine.xml to work as expected. **/ mitkNewMacro1Param(Self, const char*); /** \brief Callback for modifications in observed SliceNavigationControllers -- forwards to UpdateRotatableSNCs(). This method is called when an observed SliceNavigationController changes its world geometry. The connection is established by calling the other SliceNavigationController's method ConnectGeometrySendEvent (or similar). */ virtual void SetGeometry(const itk::EventObject& EventObject); /** \brief NOT USED by anything open-source. Deprecated. Highly obfuscated code. Use SliceNavigationController::ReorientSlices() instead! #Deprecated */ virtual void RotateToPoint( SliceNavigationController *rotationPlaneSNC, SliceNavigationController *rotatedPlaneSNC, const Point3D &point, bool linked = false ); protected: SlicesRotator(const char* machine); virtual ~SlicesRotator(); /** \brief Called from SlicesCoordinator after a new controller is added (to internal list m_SliceNavigationControllers). */ virtual void OnSliceControllerAdded(SliceNavigationController* snc); /* \brief Called from SlicesCoordinator after a new controller is being removed (to internal list m_SliceNavigationControllers). */ virtual void OnSliceControllerRemoved(SliceNavigationController* snc); /** \brief Check all observed SliceNavigationControllers: remember those that are rotatable in m_RotatableSNCs. */ virtual void UpdateRotatableSNCs(); // following methods called from superclass ExecuteAction bool DoSelectSlice(Action*, const StateEvent*); bool DoDecideBetweenRotationAndSliceSelection(Action*, const StateEvent*); bool DoStartRotation(Action*, const StateEvent*); bool DoEndRotation(Action*, const StateEvent*); bool DoRotationStep(Action*, const StateEvent*); SNCVector m_RotatableSNCs; /// all SNCs that currently have CreatedWorldGeometries, that can be rotated. SNCVector m_SNCsToBeRotated; /// all SNCs that will be rotated (exceptions are the ones parallel to the one being clicked) Point3D m_LastCursorPosition; /// used for calculation of the rotation angle Point3D m_CenterOfRotation; /// used for calculation of the rotation angle }; } // namespace #endif diff --git a/Core/Code/Controllers/mitkSlicesSwiveller.h b/Core/Code/Controllers/mitkSlicesSwiveller.h index c01ea9466d..143fb8ec8a 100644 --- a/Core/Code/Controllers/mitkSlicesSwiveller.h +++ b/Core/Code/Controllers/mitkSlicesSwiveller.h @@ -1,119 +1,119 @@ /*=================================================================== 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. ===================================================================*/ #ifndef SLICESSWIVELLER_H_HEADER_INCLUDED #define SLICESSWIVELLER_H_HEADER_INCLUDED #include -#include +#include #pragma GCC visibility push(default) #include #pragma GCC visibility pop namespace mitk { /** * \brief Enables arbitrary rotation of visible slices around a swivel point * (for sliced geometries). * \ingroup NavigationControl * * This class takes care of several SliceNavigationControllers and handles * slice selection / slice rotation. It is added as listener to * GlobalInteraction by QmitkStdMultiWidget. * * The SlicesSwiveller class adds the possibility of slice rotation to the * "normal" behaviour of SliceNavigationControllers. This additional class * is needed, because one has to be aware of several "visible slices" * (selected Geometry2Ds of some SliceNavigationControllers) in order to * choose between rotation and slice selection. * * Rotation is achieved by modifying (rotating) the generated * TimeSlicedGeometry of the corresponding SliceNavigationController. * * With SlicesSwiveller, slice rotation works as follows: the user clicks onto * a 2D view (2D plane) and drags the mouse; the relative direction and angle * of the dragged mouse movement directly effects the rotation axis and * angle. If "LinkPlanes" is set to true, the rotation is applied to the * planes of all registered SNCs, not only of the one associated with the * plane clicked on. * * In contrast to the situation without the SlicesRotator, the * SliceNavigationControllers are now not directly registered as listeners to * GlobalInteraction. SlicesRotator is registered as a listener and decides * whether something should be rotated or whether another slice should be * selected. In the latter case, a PositionEvent is just forwarded to the * SliceNavigationController. * * \sa SlicesRotator */ class MITK_CORE_EXPORT SlicesSwiveller : public SlicesCoordinator { public: mitkClassMacro(SlicesSwiveller, SlicesCoordinator); static Pointer New(); /** * @brief New Macro with one parameter for creating this object with static New(..) method **/ mitkNewMacro1Param(Self, const char*); virtual void SetGeometry(const itk::EventObject& EventObject); protected: SlicesSwiveller(const char* machine); // clear list of controllers virtual ~SlicesSwiveller(); // check if the slices of this SliceNavigationController can be rotated (???) Possible virtual void OnSliceControllerAdded(SliceNavigationController* snc); virtual void OnSliceControllerRemoved(SliceNavigationController* snc); virtual void UpdateRelevantSNCs(); virtual bool ExecuteAction(Action * action, StateEvent const* stateEvent); /** All SNCs that currently have CreatedWorldGeometries, that can be rotated */ SNCVector m_RelevantSNCs; /** SNCs that will be rotated (clicked plane + all relevant others, if linked) */ SNCVector m_SNCsToBeRotated; Point3D m_LastCursorPosition; Point3D m_CenterOfRotation; Point2D m_ReferenceCursor; Vector3D m_RotationPlaneNormal; Vector3D m_RotationPlaneXVector; Vector3D m_RotationPlaneYVector; Vector3D m_PreviousRotationAxis; ScalarType m_PreviousRotationAngle; }; } // namespace #endif diff --git a/Core/Code/Controllers/mitkStepper.h b/Core/Code/Controllers/mitkStepper.h index ff9faf8c0e..9a7a7959da 100644 --- a/Core/Code/Controllers/mitkStepper.h +++ b/Core/Code/Controllers/mitkStepper.h @@ -1,151 +1,151 @@ /*=================================================================== 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. ===================================================================*/ #ifndef STEPPER_H_HEADER_INCLUDED_C1E77191 #define STEPPER_H_HEADER_INCLUDED_C1E77191 #include #include -#include "mitkVector.h" +#include "mitkTypes.h" #include #include #include namespace mitk { /** * \brief Helper class to step through a list * * A helper class to step through a list. Does not contain the list, just the * position in the list (between 0 and GetSteps()). Provides methods like * First (go to the first element), Next (go to the next one), etc. * * Besides the actual number of steps, the stepper can also hold a stepping * range, indicating the scalar values corresponding to the covered steps. * For example, steppers are generally used to slice a dataset with a plane; * Hereby, Steps indicates the total number of steps (positions) available for * the plane, Pos indicates the current step, and Range indicates the physical * minimum and maximum values for the plane, in this case a value in mm. * * The range can also be supplied with a unit name (a string) which can be * used by classes providing information about the stepping (e.g. graphical * sliders). * * \ingroup NavigationControl */ class MITK_CORE_EXPORT Stepper : public itk::Object { public: mitkClassMacro(Stepper, itk::Object); itkNewMacro(Self); itkGetMacro(Pos, unsigned int); virtual void SetPos(unsigned int pos) { // copied from itkMacro.h, itkSetClampMacro(...) unsigned int newPos; if ( m_Steps != 0 ) { newPos = (pos > m_Steps-1 ? m_Steps-1 : pos); } else { newPos = 0; } if (this->m_Pos != newPos ) { this->m_Pos = newPos ; this->Modified(); } } itkGetMacro(Steps, unsigned int); itkSetMacro(Steps, unsigned int); itkGetMacro(AutoRepeat, bool); itkSetMacro(AutoRepeat, bool); itkBooleanMacro(AutoRepeat); /** Causes the stepper to shift direction when the boundary is reached */ itkSetMacro(PingPong, bool); itkGetMacro(PingPong, bool); itkBooleanMacro(PingPong); /** If set to true, the Next() decreases the stepper and Previous() * decreases it */ itkSetMacro(InverseDirection, bool); itkGetMacro(InverseDirection, bool); itkBooleanMacro(InverseDirection); void SetRange( ScalarType min, ScalarType max ); void InvalidateRange(); ScalarType GetRangeMin() const; ScalarType GetRangeMax() const; bool HasValidRange() const; void RemoveRange(); bool HasRange() const; void SetUnitName( const char *unitName ); const char *GetUnitName() const; void RemoveUnitName(); bool HasUnitName() const; virtual void Next(); virtual void Previous(); virtual void First(); virtual void Last(); protected: Stepper(); virtual ~Stepper(); void Increase(); void Decrease(); unsigned int m_Pos; unsigned int m_Steps; bool m_AutoRepeat; bool m_PingPong; bool m_InverseDirection; ScalarType m_RangeMin; ScalarType m_RangeMax; bool m_RangeValid; bool m_HasRange; std::string m_UnitName; bool m_HasUnitName; }; } // namespace mitk #endif /* STEPPER_H_HEADER_INCLUDED_C1E77191 */ diff --git a/Core/Code/DataManagement/itkVtkAbstractTransform.txx b/Core/Code/DataManagement/itkVtkAbstractTransform.txx index 66aaba9d27..83be3971a3 100644 --- a/Core/Code/DataManagement/itkVtkAbstractTransform.txx +++ b/Core/Code/DataManagement/itkVtkAbstractTransform.txx @@ -1,250 +1,250 @@ /*=================================================================== 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 "itkVtkAbstractTransform.h" #include -#include +#include namespace itk { template itk::VtkAbstractTransform::VtkAbstractTransform() : m_VtkAbstractTransform(NULL), m_InverseVtkAbstractTransform(NULL), m_LastVtkAbstractTransformTimeStamp(0) { } template itk::VtkAbstractTransform::~VtkAbstractTransform() { if(m_VtkAbstractTransform!=NULL) m_VtkAbstractTransform->UnRegister(NULL); } template vtkAbstractTransform* itk::VtkAbstractTransform::GetVtkAbstractTransform() const { return m_VtkAbstractTransform; } template vtkAbstractTransform* itk::VtkAbstractTransform::GetInverseVtkAbstractTransform() const { return m_InverseVtkAbstractTransform; } template void itk::VtkAbstractTransform::SetVtkAbstractTransform(vtkAbstractTransform* aVtkAbstractTransform) { if(m_VtkAbstractTransform==aVtkAbstractTransform) return; if(m_VtkAbstractTransform!=NULL) m_VtkAbstractTransform->UnRegister(NULL); m_VtkAbstractTransform=aVtkAbstractTransform; if(m_VtkAbstractTransform!=NULL) { m_VtkAbstractTransform->Register(NULL); m_InverseVtkAbstractTransform=m_VtkAbstractTransform->GetInverse(); // memory managed by m_VtkAbstractTransform } m_LastVtkAbstractTransformTimeStamp = m_VtkAbstractTransform->GetMTime(); this->Modified(); } // Transform a point template typename itk::VtkAbstractTransform::OutputPointType itk::VtkAbstractTransform:: TransformPoint(const InputPointType &point) const { assert(m_VtkAbstractTransform!=NULL); OutputPointType outputpoint; vnl_vector vnl_vec; mitk::ScalarType vtkpt[3]; mitk::itk2vtk(point, vtkpt); m_VtkAbstractTransform->TransformPoint(vtkpt, vtkpt); mitk::vtk2itk(vtkpt, outputpoint); return outputpoint; } // Transform a vector template typename itk::VtkAbstractTransform::OutputVectorType itk::VtkAbstractTransform:: TransformVector(const InputVectorType &vect) const { assert(m_VtkAbstractTransform!=NULL); OutputVectorType outputvector; vnl_vector vnl_vec; mitk::ScalarType vtkpt[3]={0,0,0}; mitk::ScalarType vtkvec[3]; mitk::vnl2vtk(vect.GetVnlVector(), vtkvec); m_VtkAbstractTransform->TransformVectorAtPoint(vtkpt, vtkvec, vtkvec); mitk::vtk2itk(vtkvec, outputvector); return outputvector; } // Transform a vnl_vector_fixed template typename itk::VtkAbstractTransform::OutputVnlVectorType itk::VtkAbstractTransform:: TransformVector(const InputVnlVectorType &vect) const { assert(m_VtkAbstractTransform!=NULL); OutputVnlVectorType outputvector; mitk::ScalarType vtkpt[3]={0,0,0}; mitk::ScalarType vtkvec[3]; mitk::vnl2vtk(vect, vtkvec); m_VtkAbstractTransform->TransformVectorAtPoint(vtkpt, vtkvec, vtkvec); mitk::vtk2itk(vtkvec, outputvector); return outputvector; } // Transform a CovariantVector template typename itk::VtkAbstractTransform::OutputCovariantVectorType itk::VtkAbstractTransform:: TransformCovariantVector(const InputCovariantVectorType &/*vec*/) const { itkExceptionMacro( << "implement before using!" ); OutputCovariantVectorType result; // Converted vector // for (unsigned int i = 0; i < NDimensions; i++) // { // result[i] = NumericTraits::Zero; // for (unsigned int j = 0; j < NDimensions; j++) // { // result[i] += m_Inverse[j][i]*vec[j]; // Inverse transposed // } // } return result; } // Back transform a point template typename VtkAbstractTransform::InputPointType itk::VtkAbstractTransform:: BackTransform(const OutputPointType &point) const { assert(m_VtkAbstractTransform!=NULL); OutputPointType outputpoint; mitk::ScalarType vtkpt[3]; mitk::itk2vtk(point, vtkpt); m_InverseVtkAbstractTransform->TransformPoint(vtkpt, vtkpt); mitk::vtk2itk(vtkpt, outputpoint); return outputpoint; } // Back transform a vector template typename VtkAbstractTransform::InputVectorType itk::VtkAbstractTransform:: BackTransform(const OutputVectorType &vect ) const { assert(m_VtkAbstractTransform!=NULL); OutputVectorType outputvector; mitk::ScalarType vtkpt[3]={0,0,0}; mitk::ScalarType vtkvec[3]; mitk::itk2vtk(vect, vtkvec); m_InverseVtkAbstractTransform->TransformVectorAtPoint(vtkpt, vtkvec, vtkvec); mitk::vtk2itk(vtkvec, outputvector); return outputvector; } // Back transform a vnl_vector template typename VtkAbstractTransform::InputVnlVectorType itk::VtkAbstractTransform:: BackTransform(const OutputVnlVectorType &vect ) const { assert(m_InverseVtkAbstractTransform!=NULL); OutputVnlVectorType outputvector; mitk::ScalarType vtkpt[3]={0,0,0}; mitk::ScalarType vtkvec[3]; mitk::itk2vtk(vect, vtkvec); m_InverseVtkAbstractTransform->TransformVectorAtPoint(vtkpt, vtkvec, vtkvec); mitk::vtk2itk(vtkvec, outputvector); return outputvector; } // Back Transform a CovariantVector template typename VtkAbstractTransform::InputCovariantVectorType itk::VtkAbstractTransform:: BackTransform(const OutputCovariantVectorType &vec) const { itkExceptionMacro( << "implement before using!" ); // for (unsigned int i = 0; i < NDimensions; i++) // { // result[i] = NumericTraits::Zero; // for (unsigned int j = 0; j < NDimensions; j++) // { // result[i] += m_Matrix[j][i]*vec[j]; // Direct matrix transposed // } // } return vec; } template unsigned long itk::VtkAbstractTransform::GetMTime() const { if((m_VtkAbstractTransform != NULL) && (m_LastVtkAbstractTransformTimeStamp < m_VtkAbstractTransform->GetMTime())) { m_LastVtkAbstractTransformTimeStamp=m_VtkAbstractTransform->GetMTime(); this->Modified(); } return Superclass::GetMTime(); } template void itk::VtkAbstractTransform::SetParameters(const ParametersType&) { // TODO } template void itk::VtkAbstractTransform::SetFixedParameters(const ParametersType&) { // TODO } template void itk::VtkAbstractTransform::ComputeJacobianWithRespectToParameters(const InputPointType&, JacobianType&) const { // TODO } template void itk::VtkAbstractTransform::ComputeJacobianWithRespectToPosition(const InputPointType&, JacobianType&) const { // TODO } } // namespace itk diff --git a/Core/Code/DataManagement/mitkAnnotationProperty.h b/Core/Code/DataManagement/mitkAnnotationProperty.h index f0385ff5cc..c6f9e9eac7 100644 --- a/Core/Code/DataManagement/mitkAnnotationProperty.h +++ b/Core/Code/DataManagement/mitkAnnotationProperty.h @@ -1,91 +1,91 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKANNOTATIONPROPERTY_H_HEADER_INCLUDED #define MITKANNOTATIONPROPERTY_H_HEADER_INCLUDED #include #include "mitkBaseProperty.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include #include namespace mitk { /** * \brief Property for annotations * \ingroup DataManagement */ class MITK_CORE_EXPORT AnnotationProperty : public BaseProperty { public: mitkClassMacro(AnnotationProperty, BaseProperty); typedef std::string ValueType; itkNewMacro( AnnotationProperty ); mitkNewMacro2Param( AnnotationProperty, const char *, const Point3D & ); mitkNewMacro2Param( AnnotationProperty, const std::string &, const Point3D & ); mitkNewMacro4Param( AnnotationProperty, const char *, ScalarType, ScalarType, ScalarType ); mitkNewMacro4Param( AnnotationProperty, const std::string &, ScalarType, ScalarType, ScalarType ); itkGetStringMacro( Label ); itkSetStringMacro( Label ); const Point3D &GetPosition() const; void SetPosition( const Point3D &position ); virtual std::string GetValueAsString() const; virtual BaseProperty& operator=(const BaseProperty& other) { return Superclass::operator=(other); } \ using BaseProperty::operator =; protected: std::string m_Label; Point3D m_Position; AnnotationProperty(); AnnotationProperty( const char *label, const Point3D &position ); AnnotationProperty( const std::string &label, const Point3D &position ); AnnotationProperty( const char *label, ScalarType x, ScalarType y, ScalarType z ); AnnotationProperty( const std::string &label, ScalarType x, ScalarType y, ScalarType z ); AnnotationProperty(const AnnotationProperty& other); private: // purposely not implemented AnnotationProperty& operator=(const AnnotationProperty&); itk::LightObject::Pointer InternalClone() const; virtual bool IsEqual(const BaseProperty& property) const; virtual bool Assign(const BaseProperty & property); }; } // namespace mitk #endif /* MITKANNOTATIONPROPERTY_H_HEADER_INCLUDED */ diff --git a/Core/Code/DataManagement/mitkApplicationCursor.h b/Core/Code/DataManagement/mitkApplicationCursor.h index 780cf7d945..7f78355044 100644 --- a/Core/Code/DataManagement/mitkApplicationCursor.h +++ b/Core/Code/DataManagement/mitkApplicationCursor.h @@ -1,109 +1,109 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITK_APPLICATION_CURSOR_H_DEFINED_AND_ALL_IS_GOOD #define MITK_APPLICATION_CURSOR_H_DEFINED_AND_ALL_IS_GOOD #include -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { /*! \brief Toolkit specific implementation of mitk::ApplicationCursor For any toolkit, this class has to be sub-classed. One instance of that sub-class has to be registered with mitk::ApplicationCursor. See the (very simple) implmentation of QmitkApplicationCursor for an example. */ class MITK_CORE_EXPORT ApplicationCursorImplementation { public: /// Change the current application cursor virtual void PushCursor(const char* XPM[], int hotspotX, int hotspotY) = 0; /// Change the current application cursor virtual void PushCursor(std::istream&, int hotspotX, int hotspotY) = 0; /// Restore the previous cursor virtual void PopCursor() = 0; /// Get absolute mouse position on screen virtual const Point2I GetCursorPosition() = 0; /// Set absolute mouse position on screen virtual void SetCursorPosition(const Point2I&) = 0; virtual ~ApplicationCursorImplementation() {} protected: private: }; /*! \brief Allows to override the application's cursor. Base class for classes that allow to override the applications cursor with context dependent cursors. Accepts cursors in the XPM format. The behaviour is stack-like. You can push your cursor on top of the stack and later pop it to reset the cursor to its former state. This is mimicking Qt's Application::setOverrideCuror() behaviour, but should be ok for most cases where you want to switch a cursor. */ class MITK_CORE_EXPORT ApplicationCursor { public: /// This class is a singleton. static ApplicationCursor* GetInstance(); /// To be called by a toolkit specific ApplicationCursorImplementation. static void RegisterImplementation(ApplicationCursorImplementation* implementation); /// Change the current application cursor void PushCursor(const char* XPM[], int hotspotX = -1, int hotspotY = -1); /// Change the current application cursor void PushCursor(std::istream&, int hotspotX = -1, int hotspotY = -1); /// Restore the previous cursor void PopCursor(); /// Get absolute mouse position on screen /// \return (-1, -1) if querying mouse position is not possible const Point2I GetCursorPosition(); /// Set absolute mouse position on screen void SetCursorPosition(const Point2I&); protected: /// Purposely hidden - singleton ApplicationCursor(); private: static ApplicationCursorImplementation* m_Implementation; }; } // namespace #endif diff --git a/Core/Code/DataManagement/mitkClippingProperty.h b/Core/Code/DataManagement/mitkClippingProperty.h index a600d809f1..8d779a910a 100644 --- a/Core/Code/DataManagement/mitkClippingProperty.h +++ b/Core/Code/DataManagement/mitkClippingProperty.h @@ -1,95 +1,95 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKCLIPPINGPROPERTY_H_HEADER_INCLUDED #define MITKCLIPPINGPROPERTY_H_HEADER_INCLUDED #include #include "mitkBaseProperty.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include #include namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /** * \brief Property for clipping datasets; currently only * clipping planes are possible * \ingroup DataManagement */ class MITK_CORE_EXPORT ClippingProperty : public BaseProperty { public: mitkClassMacro(ClippingProperty, BaseProperty); typedef std::string ValueType; itkNewMacro( ClippingProperty ); mitkNewMacro2Param( ClippingProperty, const Point3D &, const Vector3D & ); bool GetClippingEnabled() const; void SetClippingEnabled( bool enabled ); const Point3D &GetOrigin() const; void SetOrigin( const Point3D &origin ); const Vector3D &GetNormal() const; void SetNormal( const Vector3D &normal ); virtual std::string GetValueAsString() const; using BaseProperty::operator =; protected: bool m_ClippingEnabled; Point3D m_Origin; Vector3D m_Normal; ClippingProperty(); ClippingProperty(const ClippingProperty& other); ClippingProperty( const Point3D &origin, const Vector3D &normal ); private: // purposely not implemented ClippingProperty& operator=(const ClippingProperty&); virtual bool IsEqual(const BaseProperty& property) const; virtual bool Assign(const BaseProperty& property); virtual itk::LightObject::Pointer InternalClone() const; }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace mitk #endif /* MITKCLIPPINGPROPERTY_H_HEADER_INCLUDED */ diff --git a/Core/Code/DataManagement/mitkGenericLookupTable.h b/Core/Code/DataManagement/mitkGenericLookupTable.h index dd5b4f1672..21788db797 100644 --- a/Core/Code/DataManagement/mitkGenericLookupTable.h +++ b/Core/Code/DataManagement/mitkGenericLookupTable.h @@ -1,161 +1,161 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKGENERICLOOKUPTABLE_H_HEADER_INCLUDED_C1061CEE #define MITKGENERICLOOKUPTABLE_H_HEADER_INCLUDED_C1061CEE #include #include #include #include #include -#include "mitkVector.h" +#include "mitkTypes.h" #include namespace mitk { /** * @brief Template class for generating lookup-tables * * This class template can be instantiated for all classes/internal types that fulfills * these requirements: * - an operator<< so that the properties value can be put into a std::stringstream * - an operator== so that two properties can be checked for equality * * The main purpose of this class is to be used in conjunction with * GenericLookupTableProperty. This enables passing of arbitrary lookup * tables to mappers to configure the rendering process. */ template class GenericLookupTable { public: typedef unsigned int IdentifierType; typedef T ValueType; typedef std::map< IdentifierType, ValueType > LookupTableType; typedef GenericLookupTable Self; GenericLookupTable() {} virtual ~GenericLookupTable() { } virtual const char *GetNameOfClass() const { return "GenericLookupTable"; } void SetTableValue( IdentifierType id, ValueType value ) { m_LookupTable[id] = value; } bool ValueExists(IdentifierType id) const { typename LookupTableType::const_iterator it = m_LookupTable.find(id); return (it != m_LookupTable.end()); } ValueType GetTableValue( IdentifierType id ) const { typename LookupTableType::const_iterator it = m_LookupTable.find(id); if (it != m_LookupTable.end()) return it->second; else throw std::range_error("id does not exist in the lookup table"); } const LookupTableType& GetLookupTable() const { return m_LookupTable; } bool operator==( const Self& lookupTable ) const { return (m_LookupTable == lookupTable.m_LookupTable); } bool operator!=( const Self& lookupTable ) const { return !(m_LookupTable == lookupTable.m_LookupTable); } virtual Self& operator=(const Self& other) // \TODO: this needs to be unit tested! { if ( this == &other ) { return *this; } else { m_LookupTable.clear(); m_LookupTable = other.m_LookupTable; return *this; } } protected: LookupTableType m_LookupTable; }; } // namespace mitk /** * Generates a specialized subclass of mitk::GenericLookupTable. * This way, GetNameOfClass() returns the value provided by LookupTableName. * Please see mitkProperties.h for examples. * @param LookupTableName the name of the instantiation of GenericLookupTable * @param Type the value type of the GenericLookupTable */ #define mitkSpecializeGenericLookupTable(LookupTableName,Type) \ class MITK_CORE_EXPORT LookupTableName: public GenericLookupTable< Type > \ { \ public: \ typedef LookupTableName Self; \ typedef GenericLookupTable< Type > Superclass; \ virtual const char *GetNameOfClass() const \ {return #LookupTableName;} \ LookupTableName() {} \ virtual Superclass& operator=(const Superclass& other) { return Superclass::operator=(other); } \ virtual ~LookupTableName() {} \ }; \ MITK_CORE_EXPORT std::ostream& operator<<(std::ostream& stream, const LookupTableName& /*l*/); /** * Generates the ostream << operator for the lookuptable. This definition * of a global function must be in a cpp file, therefore it is split from the * class declaration macro mitkSpecializeGenericLookupTable. */ #define mitkSpecializeGenericLookupTableOperator(LookupTableName) \ std::ostream& mitk::operator<<(std::ostream& stream, const LookupTableName& l) \ { \ typedef LookupTableName::LookupTableType::const_iterator IterType; \ IterType e = l.GetLookupTable().end(); \ IterType b = l.GetLookupTable().begin(); \ stream << "["; \ for (IterType i = b; i != e; ++i) \ { \ if (i != b) \ { \ stream << ", "; \ } \ stream << i->first << " -> " << i->second; \ } \ return stream << "]"; \ }; #endif diff --git a/Core/Code/DataManagement/mitkGenericProperty.h b/Core/Code/DataManagement/mitkGenericProperty.h index 3437bc9973..fd4a45f542 100644 --- a/Core/Code/DataManagement/mitkGenericProperty.h +++ b/Core/Code/DataManagement/mitkGenericProperty.h @@ -1,146 +1,146 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKGENERICPROPERTY_H_HEADER_INCLUDED_C1061CEE #define MITKGENERICPROPERTY_H_HEADER_INCLUDED_C1061CEE #include #include #include -#include "mitkVector.h" +#include "mitkTypes.h" #include #include "mitkBaseProperty.h" namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /*! @ brief Template class for generating properties for int, float, bool, etc. This class template can be instantiated for all classes/internal types that fulfills these requirements: - an operator<< so that the properties value can be put into a std::stringstream - an operator== so that two properties can be checked for equality Note: you must use the macro mitkSpecializeGenericProperty to provide specializations for concrete types (e.g. BoolProperty). Please see mitkProperties.h for examples. If you don't use the mitkSpecializeGenericProperty Macro, GetNameOfClass() returns a wrong name. */ template class MITK_EXPORT GenericProperty : public BaseProperty { public: mitkClassMacro(GenericProperty, BaseProperty); mitkNewMacro1Param(GenericProperty, T); itkCloneMacro(Self) typedef T ValueType; itkSetMacro(Value,T); itkGetConstMacro(Value,T); virtual std::string GetValueAsString() const { std::stringstream myStr; myStr << GetValue() ; return myStr.str(); } using BaseProperty::operator=; protected: GenericProperty() {} GenericProperty(T x) : m_Value(x) {} GenericProperty(const GenericProperty& other) : BaseProperty(other) , m_Value(other.m_Value) {} T m_Value; private: // purposely not implemented GenericProperty& operator=(const GenericProperty&); virtual itk::LightObject::Pointer InternalClone() const { itk::LightObject::Pointer result(new Self(*this)); return result; } virtual bool IsEqual(const BaseProperty& other) const { return (this->m_Value == static_cast(other).m_Value); } virtual bool Assign(const BaseProperty& other) { this->m_Value = static_cast(other).m_Value; return true; } }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace mitk /** * Generates a specialized subclass of mitk::GenericProperty. * This way, GetNameOfClass() returns the value provided by PropertyName. * Please see mitkProperties.h for examples. * @param PropertyName the name of the subclass of GenericProperty * @param Type the value type of the GenericProperty * @param Export the export macro for DLL usage */ #define mitkDeclareGenericProperty(PropertyName,Type,Export) \ class Export PropertyName: public GenericProperty< Type > \ { \ public: \ mitkClassMacro(PropertyName, GenericProperty< Type >); \ itkNewMacro(PropertyName); \ mitkNewMacro1Param(PropertyName, Type); \ using BaseProperty::operator=; \ protected: \ PropertyName(); \ PropertyName(const PropertyName&); \ PropertyName(Type x); \ private: \ itk::LightObject::Pointer InternalClone() const; \ }; #define mitkDefineGenericProperty(PropertyName,Type,DefaultValue) \ mitk::PropertyName::PropertyName() : Superclass(DefaultValue) { } \ mitk::PropertyName::PropertyName(const PropertyName& other) : GenericProperty< Type >(other) {} \ mitk::PropertyName::PropertyName(Type x) : Superclass(x) {} \ itk::LightObject::Pointer mitk::PropertyName::InternalClone() const { \ itk::LightObject::Pointer result(new Self(*this)); \ return result; \ } \ #endif /* MITKGENERICPROPERTY_H_HEADER_INCLUDED_C1061CEE */ diff --git a/Core/Code/DataManagement/mitkGeometry3D.h b/Core/Code/DataManagement/mitkGeometry3D.h index 3f5bdd424e..99aeb8f2ae 100644 --- a/Core/Code/DataManagement/mitkGeometry3D.h +++ b/Core/Code/DataManagement/mitkGeometry3D.h @@ -1,669 +1,669 @@ /*=================================================================== 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. ===================================================================*/ #ifndef GEOMETRY3D_H_HEADER_INCLUDED_C1EBD0AD #define GEOMETRY3D_H_HEADER_INCLUDED_C1EBD0AD #include #include -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkOperationActor.h" #include #include #include #include class vtkLinearTransform; class vtkMatrixToLinearTransform; class vtkMatrix4x4; namespace mitk { //##Documentation //## @brief Standard 3D-BoundingBox typedef //## //## Standard 3D-BoundingBox typedef to get rid of template arguments (3D, type). typedef itk::BoundingBox BoundingBox; //##Documentation //## @brief Standard typedef for time-bounds typedef itk::FixedArray TimeBounds; typedef itk::FixedArray FixedArrayType; typedef itk::AffineGeometryFrame AffineGeometryFrame3D; //##Documentation //## @brief Describes the geometry of a data object //## //## At least, it can return the bounding box of the data object. //## //## The class holds //## \li a bounding box which is axes-parallel in intrinsic coordinates //## (often integer indices of pixels), to be accessed by //## GetBoundingBox() //## \li a transform to convert intrinsic coordinates into a //## world-coordinate system with coordinates in millimeters //## and milliseconds (all are floating point values), to //## be accessed by GetIndexToWorldTransform() //## \li a life span, i.e. a bounding box in time in ms (with //## start and end time), to be accessed by GetTimeBounds(). //## The default is minus infinity to plus infinity. //## //## Geometry3D and its sub-classes allow converting between //## intrinsic coordinates (called index or unit coordinates) //## and world-coordinates (called world or mm coordinates), //## e.g. WorldToIndex. //## In case you need integer index coordinates, provide an //## mitk::Index3D (or itk::Index) as target variable to //## WorldToIndex, otherwise you will get a continuous index //## (floating point values). //## //## An important sub-class is SlicedGeometry3D, which descibes //## data objects consisting of slices, e.g., objects of type Image. //## Conversions between world coordinates (in mm) and unit coordinates //## (e.g., pixels in the case of an Image) can be performed. //## //## For more information on related classes, see \ref Geometry. //## //## Geometry3D instances referring to an Image need a slightly //## different definition of corners, see SetImageGeometry. This //## is usualy automatically called by Image. //## //## Geometry3D have to be initialized in the method GenerateOutputInformation() //## of BaseProcess (or CopyInformation/ UpdateOutputInformation of BaseData, //## if possible, e.g., by analyzing pic tags in Image) subclasses. See also //## itk::ProcessObject::GenerateOutputInformation(), //## itk::DataObject::CopyInformation() and //## itk::DataObject::UpdateOutputInformation(). //## //## Rule: everything is in mm (ms) if not stated otherwise. //## @ingroup Geometry class MITK_CORE_EXPORT Geometry3D : public AffineGeometryFrame3D, public OperationActor { public: mitkClassMacro(Geometry3D, AffineGeometryFrame3D); typedef itk::QuaternionRigidTransform< ScalarType > QuaternionTransformType; typedef QuaternionTransformType::VnlQuaternionType VnlQuaternionType; /** Method for creation through the object factory. */ itkNewMacro(Self); // a bit of a misuse, but we want only doxygen to see the following: #ifdef DOXYGEN_SKIP //##Documentation //## @brief Get the transformation used to convert from index //## to world coordinates itkGetObjectMacro(IndexToWorldTransform, AffineTransform3D); #endif //## @brief Set the transformation used to convert from index //## to world coordinates virtual void SetIndexToWorldTransform(mitk::AffineTransform3D* transform); //##Documentation //## @brief Convenience method for setting the ITK transform //## (m_IndexToWorldTransform) via an vtkMatrix4x4 //## \sa SetIndexToWorldTransform virtual void SetIndexToWorldTransformByVtkMatrix(vtkMatrix4x4* vtkmatrix); #ifdef DOXYGEN_SKIP //##Documentation //## @brief Get bounding box (in index/unit coordinates) itkGetConstObjectMacro(BoundingBox, BoundingBoxType); //##Documentation //## @brief Get bounding box (in index/unit coordinates) as a BoundsArrayType const BoundsArrayType GetBounds() const { assert(m_BoundingBox.IsNotNull()); return m_BoundingBox->GetBounds(); } //##Documentation //## \brief Set the bounding box (in index/unit coordinates) //## //## Only possible via the BoundsArray to make clear that a //## copy of the bounding-box is stored, not a reference to it. virtual void SetBounds(const BoundsArrayType& bounds); #endif //##Documentation //## @brief Set the bounding box (in index/unit coordinates) via a float array virtual void SetFloatBounds(const float bounds[6]); //##Documentation //## @brief Set the bounding box (in index/unit coordinates) via a double array virtual void SetFloatBounds(const double bounds[6]); //##Documentation //## @brief When switching from an Image Geometry to a normal Geometry (and the other way around), you have to change the origin as well (See Geometry Documentation)! This function will change the "isImageGeometry" bool flag and changes the origin respectively. virtual void ChangeImageGeometryConsideringOriginOffset( const bool isAnImageGeometry ); //##Documentation //## @brief Checks, if the given geometry can be converted to 2D without information loss //## e.g. when a 2D image is saved, the matrix is usually cropped to 2x2, and when you load it back to MITK //## it will be filled with standard values. This function checks, if information would be lost during this //## procedure virtual bool Is2DConvertable(); //##Documentation //## @brief Get the time bounds (in ms) itkGetConstReferenceMacro(TimeBounds, TimeBounds); //##Documentation //## @brief Set the time bounds (in ms) virtual void SetTimeBounds(const TimeBounds& timebounds); //##Documentation //## @brief Get the position of the corner number \a id (in world coordinates) //## //## See SetImageGeometry for how a corner is defined on images. Point3D GetCornerPoint(int id) const; //##Documentation //## @brief Get the position of a corner (in world coordinates) //## //## See SetImageGeometry for how a corner is defined on images. Point3D GetCornerPoint(bool xFront=true, bool yFront=true, bool zFront=true) const; //##Documentation //## @brief Get vector along bounding-box in the specified @a direction in mm //## //## The length of the vector is the size of the bounding-box in the //## specified @a direction in mm //## \sa GetMatrixColumn Vector3D GetAxisVector(unsigned int direction) const { Vector3D frontToBack; frontToBack.SetVnlVector(m_IndexToWorldTransform->GetMatrix().GetVnlMatrix().get_column(direction)); frontToBack *= GetExtent(direction); return frontToBack; } //##Documentation //## @brief Get the center of the bounding-box in mm //## Point3D GetCenter() const { assert(m_BoundingBox.IsNotNull()); return m_IndexToWorldTransform->TransformPoint(m_BoundingBox->GetCenter()); } //##Documentation //## @brief Get the squared length of the diagonal of the bounding-box in mm //## double GetDiagonalLength2() const { Vector3D diagonalvector = GetCornerPoint()-GetCornerPoint(false, false, false); return diagonalvector.GetSquaredNorm(); } //##Documentation //## @brief Get the length of the diagonal of the bounding-box in mm //## double GetDiagonalLength() const { return sqrt(GetDiagonalLength2()); } //##Documentation //## @brief Get a VnlVector along bounding-box in the specified //## @a direction, length is spacing //## //## \sa GetAxisVector VnlVector GetMatrixColumn(unsigned int direction) const { return m_IndexToWorldTransform->GetMatrix().GetVnlMatrix().get_column(direction); } #ifdef DOXYGEN_SKIP //##Documentation //## @brief Get the extent of the bounding box (in index/unit coordinates) //## //## To access the extent in mm use GetExtentInMM ScalarType GetExtent(unsigned int direction) const; #endif //##Documentation //## @brief Get the extent of the bounding-box in the specified @a direction in mm //## //## Equals length of GetAxisVector(direction). ScalarType GetExtentInMM(int direction) const { return m_IndexToWorldTransform->GetMatrix().GetVnlMatrix().get_column(direction).magnitude()*GetExtent(direction); } //##Documentation //## @brief Set the extent of the bounding-box in the specified @a direction in mm //## //## @note This changes the matrix in the transform, @a not the bounds, which are given in units! virtual void SetExtentInMM(int direction, ScalarType extentInMM); //##Documentation //## @brief Get the m_IndexToWorldTransform as a vtkLinearTransform vtkLinearTransform* GetVtkTransform() const { return (vtkLinearTransform*)m_VtkIndexToWorldTransform; } //##Documentation //## @brief Set the origin, i.e. the upper-left corner of the plane //## virtual void SetOrigin(const Point3D& origin); //##Documentation //## @brief Translate the origin by a vector //## virtual void Translate(const Vector3D& vector); //##Documentation //## @brief Set the transform to identity //## virtual void SetIdentity(); //##Documentation //## @brief Compose new IndexToWorldTransform with a given transform. //## //## This method composes m_IndexToWorldTransform with another transform, //## modifying self to be the composition of self and other. //## If the argument pre is true, then other is precomposed with self; //## that is, the resulting transformation consists of first applying //## other to the source, followed by self. If pre is false or omitted, //## then other is post-composed with self; that is the resulting //## transformation consists of first applying self to the source, //## followed by other. virtual void Compose( const AffineGeometryFrame3D::TransformType * other, bool pre = 0 ); //##Documentation //## @brief Compose new IndexToWorldTransform with a given vtkMatrix4x4. //## //## Converts the vtkMatrix4x4 into a itk-transform and calls the previous method. virtual void Compose( const vtkMatrix4x4 * vtkmatrix, bool pre = 0 ); //##Documentation //## @brief Get the origin, e.g. the upper-left corner of the plane const Point3D& GetOrigin() const { return m_Origin; } //##Documentation //## @brief Get the origin as VnlVector //## //## \sa GetOrigin VnlVector GetOriginVnl() const { return const_cast(this)->m_Origin.GetVnlVector(); } //##Documentation //## @brief Convert world coordinates (in mm) of a \em point to (continuous!) index coordinates //## \warning If you need (discrete) integer index coordinates (e.g., for iterating easily over an image), //## use WorldToIndex(const mitk::Point3D& pt_mm, itk::Index &index). //## For further information about coordinates types, please see the Geometry documentation void WorldToIndex(const mitk::Point3D& pt_mm, mitk::Point3D& pt_units) const; //##Documentation //## @brief Convert (continuous or discrete) index coordinates of a \em point to world coordinates (in mm) //## For further information about coordinates types, please see the Geometry documentation void IndexToWorld(const mitk::Point3D& pt_units, mitk::Point3D& pt_mm) const; //##Documentation //## @brief Convert world coordinates (in mm) of a \em vector //## \a vec_mm to (continuous!) index coordinates. //## @deprecated First parameter (Point3D) is not used. If possible, please use void WorldToIndex(const mitk::Vector3D& vec_mm, mitk::Vector3D& vec_units) const. //## For further information about coordinates types, please see the Geometry documentation void WorldToIndex(const mitk::Point3D& atPt3d_mm, const mitk::Vector3D& vec_mm, mitk::Vector3D& vec_units) const; //##Documentation //## @brief Convert world coordinates (in mm) of a \em vector //## \a vec_mm to (continuous!) index coordinates. //## For further information about coordinates types, please see the Geometry documentation void WorldToIndex(const mitk::Vector3D& vec_mm, mitk::Vector3D& vec_units) const; //##Documentation //## @brief Convert (continuous or discrete) index coordinates of a \em vector //## \a vec_units to world coordinates (in mm) //## @deprecated First parameter (Point3D) is not used. If possible, please use void IndexToWorld(const mitk::Vector3D& vec_units, mitk::Vector3D& vec_mm) const. //## For further information about coordinates types, please see the Geometry documentation void IndexToWorld(const mitk::Point3D& atPt3d_units, const mitk::Vector3D& vec_units, mitk::Vector3D& vec_mm) const; //##Documentation //## @brief Convert (continuous or discrete) index coordinates of a \em vector //## \a vec_units to world coordinates (in mm) //## For further information about coordinates types, please see the Geometry documentation void IndexToWorld(const mitk::Vector3D& vec_units, mitk::Vector3D& vec_mm) const; //##Documentation //## @brief Convert world coordinates (in mm) of a \em point to (discrete!) index coordinates. //## This method rounds to integer indices! //## For further information about coordinates types, please see the Geometry documentation template void WorldToIndex(const mitk::Point3D& pt_mm, itk::Index &index) const { typedef itk::Index IndexType; mitk::Point3D pt_units; this->WorldToIndex(pt_mm, pt_units); int i, dim=index.GetIndexDimension(); if(dim>3) { index.Fill(0); dim=3; } for(i=0;i( pt_units[i] ); } } //##Documentation //## @brief Deprecated for use with ITK version 3.10 or newer. //## Convert world coordinates (in mm) of a \em point to //## ITK physical coordinates (in mm, but without a possible rotation) //## //## This method is useful if you have want to access an mitk::Image //## via an itk::Image. ITK v3.8 and older did not support rotated (tilted) //## images, i.e., ITK images are always parallel to the coordinate axes. //## When accessing a (possibly rotated) mitk::Image via an itk::Image //## the rotational part of the transformation in the Geometry3D is //## simply discarded; in other word: only the origin and spacing is //## used by ITK, not the complete matrix available in MITK. //## With WorldToItkPhysicalPoint you can convert an MITK world //## coordinate (including the rotation) into a coordinate that //## can be used with the ITK image as a ITK physical coordinate //## (excluding the rotation). template void WorldToItkPhysicalPoint(const mitk::Point3D& pt_mm, itk::Point& itkPhysicalPoint) const { mitk::vtk2itk(pt_mm, itkPhysicalPoint); } //##Documentation //## @brief Deprecated for use with ITK version 3.10 or newer. //## Convert ITK physical coordinates of a \em point (in mm, //## but without a rotation) into MITK world coordinates (in mm) //## //## For more information, see WorldToItkPhysicalPoint. template void ItkPhysicalPointToWorld(const itk::Point& itkPhysicalPoint, mitk::Point3D& pt_mm) const { mitk::vtk2itk(itkPhysicalPoint, pt_mm); } //##Documentation //## @brief Initialize the Geometry3D virtual void Initialize(); //##Documentation //## @brief Is this an ImageGeometry? //## //## For more information, see SetImageGeometry itkGetConstMacro(ImageGeometry, bool); //##Documentation //## @brief Define that this Geometry3D is refering to an Image //## //## A geometry referring to an Image needs a slightly different //## definition of the position of the corners (see GetCornerPoint). //## The position of a voxel is defined by the position of its center. //## If we would use the origin (position of the (center of) the first //## voxel) as a corner and display this point, it would seem to be //## \em not at the corner but a bit within the image. Even worse for //## the opposite corner of the image: here the corner would appear //## outside the image (by half of the voxel diameter). Thus, we have //## to correct for this and to be able to do that, we need to know //## that the Geometry3D is referring to an Image. itkSetMacro(ImageGeometry, bool); itkBooleanMacro(ImageGeometry); //##Documentation //## @brief Is this Geometry3D in a state that is valid? virtual bool IsValid() const { return m_Valid; } //##Documentation //## @brief Test whether the point \a p (world coordinates in mm) is //## inside the bounding box bool IsInside(const mitk::Point3D& p) const { mitk::Point3D index; WorldToIndex(p, index); return IsIndexInside(index); } //##Documentation //## @brief Test whether the point \a p ((continous!)index coordinates in units) is //## inside the bounding box bool IsIndexInside(const mitk::Point3D& index) const { bool inside = false; //if it is an image geometry, we need to convert the index to discrete values //this is done by applying the rounding function also used in WorldToIndex (see line 323) if (m_ImageGeometry) { mitk::Point3D discretIndex; discretIndex[0]=itk::Math::RoundHalfIntegerUp( index[0] ); discretIndex[1]=itk::Math::RoundHalfIntegerUp( index[1] ); discretIndex[2]=itk::Math::RoundHalfIntegerUp( index[2] ); inside = m_BoundingBox->IsInside(discretIndex); //we have to check if the index is at the upper border of each dimension, // because the boundingbox is not centerbased if (inside) { const BoundingBox::BoundsArrayType& bounds = m_BoundingBox->GetBounds(); if((discretIndex[0] == bounds[1]) || (discretIndex[1] == bounds[3]) || (discretIndex[2] == bounds[5])) inside = false; } } else inside = m_BoundingBox->IsInside(index); return inside; } //##Documentation //## @brief Convenience method for working with ITK indices template bool IsIndexInside(const itk::Index &index) const { int i, dim=index.GetIndexDimension(); Point3D pt_index; pt_index.Fill(0); for ( i = 0; i < dim; ++i ) { pt_index[i] = index[i]; } return IsIndexInside(pt_index); } //##Documentation //## @brief Get the spacing (size of a pixel). //## itkGetConstReferenceMacro(Spacing, mitk::Vector3D); //##Documentation //## @brief Get the spacing as a float[3] array. const float* GetFloatSpacing() const; //##Documentation //## @brief Set the spacing (m_Spacing) virtual void SetSpacing(const mitk::Vector3D& aSpacing); //##Documentation //## @brief Get the DICOM FrameOfReferenceID referring to the //## used world coordinate system itkGetConstMacro(FrameOfReferenceID, unsigned int); //##Documentation //## @brief Set the DICOM FrameOfReferenceID referring to the //## used world coordinate system itkSetMacro(FrameOfReferenceID, unsigned int); //##Documentation //## @brief Copy the ITK transform //## (m_IndexToWorldTransform) to the VTK transform //## \sa SetIndexToWorldTransform void TransferItkToVtkTransform(); //##Documentation //## @brief Copy the VTK transform //## to the ITK transform (m_IndexToWorldTransform) //## \sa SetIndexToWorldTransform void TransferVtkToItkTransform(); //##Documentation //## @brief Get the parametric bounding-box //## //## See AbstractTransformGeometry for an example usage of this. itkGetConstObjectMacro(ParametricBoundingBox, BoundingBox); //##Documentation //## @brief Get the parametric bounds //## //## See AbstractTransformGeometry for an example usage of this. const BoundingBox::BoundsArrayType& GetParametricBounds() const { assert(m_ParametricBoundingBox.IsNotNull()); return m_ParametricBoundingBox->GetBounds(); } //##Documentation //## @brief Get the parametric extent //## //## See AbstractTransformGeometry for an example usage of this. mitk::ScalarType GetParametricExtent(int direction) const { assert(direction>=0 && direction<3); assert(m_ParametricBoundingBox.IsNotNull()); BoundingBoxType::BoundsArrayType bounds = m_ParametricBoundingBox->GetBounds(); return bounds[direction*2+1]-bounds[direction*2]; } //##Documentation //## @brief Get the parametric extent in mm //## //## See AbstractTransformGeometry for an example usage of this. virtual mitk::ScalarType GetParametricExtentInMM(int direction) const { return GetExtentInMM(direction); } //##Documentation //## @brief Get the parametric transform //## //## See AbstractTransformGeometry for an example usage of this. virtual const Transform3D* GetParametricTransform() const { return m_IndexToWorldTransform; } //##Documentation //## @brief Calculates a bounding-box around the geometry relative //## to a coordinate system defined by a transform //## mitk::BoundingBox::Pointer CalculateBoundingBoxRelativeToTransform(const mitk::AffineTransform3D* transform) const; //##Documentation //## @brief clones the geometry //## //## Overwrite in all sub-classes. //## Normally looks like: //## \code //## Self::Pointer newGeometry = new Self(*this); //## newGeometry->UnRegister(); //## return newGeometry.GetPointer(); //## \endcode virtual itk::LightObject::Pointer InternalClone() const; //##Documentation //##@brief executes affine operations (translate, rotate, scale) virtual void ExecuteOperation(Operation* operation); protected: Geometry3D(); Geometry3D(const Geometry3D& other); static const std::string GetTransformAsString( TransformType* transformType ); virtual ~Geometry3D(); virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; virtual void BackTransform(const mitk::Point3D& in, mitk::Point3D& out) const; //##Documentation //## @brief Deprecated virtual void BackTransform(const mitk::Point3D& at, const mitk::Vector3D& in, mitk::Vector3D& out) const; //Without redundant parameter Point3D virtual void BackTransform(const mitk::Vector3D& in, mitk::Vector3D& out) const; //##Documentation //## @brief Set the parametric bounds //## //## Protected in this class, made public in some sub-classes, e.g., //## ExternAbstractTransformGeometry. virtual void SetParametricBounds(const BoundingBox::BoundsArrayType& bounds); /** Resets sub-transforms that compose m_IndexToWorldTransform, by using * the current value of m_IndexToWorldTransform and setting the rotation * component to zero. */ virtual void ResetSubTransforms(); mutable mitk::BoundingBox::Pointer m_ParametricBoundingBox; mutable mitk::TimeBounds m_TimeBounds; vtkMatrix4x4* m_VtkMatrix; bool m_ImageGeometry; //##Documentation //## @brief Spacing of the data. Only significant if the geometry describes //## an Image (m_ImageGeometry==true). mitk::Vector3D m_Spacing; bool m_Valid; unsigned int m_FrameOfReferenceID; static const std::string INDEX_TO_OBJECT_TRANSFORM; static const std::string OBJECT_TO_NODE_TRANSFORM; static const std::string INDEX_TO_NODE_TRANSFORM; static const std::string INDEX_TO_WORLD_TRANSFORM; private: mutable TransformType::Pointer m_InvertedTransform; mutable unsigned long m_IndexToWorldTransformLastModified; VnlQuaternionType m_RotationQuaternion; float m_FloatSpacing[3]; vtkMatrixToLinearTransform* m_VtkIndexToWorldTransform; //##Documentation //## @brief Origin, i.e. upper-left corner of the plane //## Point3D m_Origin; }; } // namespace mitk #endif /* GEOMETRY3D_H_HEADER_INCLUDED_C1EBD0AD */ diff --git a/Core/Code/DataManagement/mitkLevelWindow.h b/Core/Code/DataManagement/mitkLevelWindow.h index d170d6ce78..614156d207 100644 --- a/Core/Code/DataManagement/mitkLevelWindow.h +++ b/Core/Code/DataManagement/mitkLevelWindow.h @@ -1,239 +1,239 @@ /*=================================================================== 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. ===================================================================*/ #ifndef LEVELWINDOW_H_HEADER_INCLUDED_C1F4F02C #define LEVELWINDOW_H_HEADER_INCLUDED_C1F4F02C -#include "mitkVector.h" +#include "mitkTypes.h" #include //struct mitkIpPicDescriptor; namespace mitk { class Image; //##Documentation //## @brief Class to store level/window values //## //## Current min and max value are stored in m_LowerWindowBound and m_UpperWindowBound. //## The maximum and minimum of valid value range is stored in //## m_RangeMin and m_RangeMax. //## m_DefaultLevel amd m_DefaultWindow store the initial Level/Window values for the image. //## m_DefaultRangeMin and m_DefaultRangeMax store the initial minrange and maxrange for the image. //## //## See documentation of SetAuto for information on how the //## level window is initialized from an image. //## //## @ingroup DataManagement class MITK_CORE_EXPORT LevelWindow { public: LevelWindow(ScalarType level=127.5, ScalarType window=255.0); LevelWindow(const mitk::LevelWindow& levWin); virtual ~LevelWindow(); /*! * \brief method that returns the level value, i.e. the center of * the current grey value interval */ ScalarType GetLevel() const; /*! * \brief returns the current window size, i.e the range size of the current grey value interval */ ScalarType GetWindow() const; /*! * \brief method returns the default level value for the image */ ScalarType GetDefaultLevel() const; /*! * \brief returns the default window size for the image */ ScalarType GetDefaultWindow() const; /*! * \brief Resets the level and the window value to the default values */ void ResetDefaultLevelWindow(); /*! * Returns the minimum Value of the window */ ScalarType GetLowerWindowBound() const; /*! * Returns the upper window bound value of the window */ ScalarType GetUpperWindowBound() const; /*! * To set the level and the window value */ void SetLevelWindow(ScalarType level, ScalarType window, bool expandRangesIfNecessary = true); /*! * Set the lower and upper bound of the window */ void SetWindowBounds(ScalarType lowerBound, ScalarType upperBound, bool expandRangesIfNecessary = true); /*! * sets the window to its maximum Size in scaleRange */ void SetToMaxWindowSize(); /*! * Set the range minimum and maximum value */ void SetRangeMinMax(ScalarType min, ScalarType max); /*! * Get the range minimum value */ ScalarType GetRangeMin() const; /*! * Get the range maximum value */ ScalarType GetRangeMax() const; /*! * Get the default range minimum value */ ScalarType GetDefaultLowerBound() const; /*! * Get the default range maximum value */ ScalarType GetDefaultUpperBound() const; /*! * \brief the default min and max range for image will be reset */ void ResetDefaultRangeMinMax(); /**! * \brief returns the size of the grey value range */ ScalarType GetRange() const; /*! * set the default level and window value */ void SetDefaultLevelWindow(ScalarType level, ScalarType window); /*! * set the default Bounderies */ void SetDefaultBoundaries(ScalarType low, ScalarType up); /**! * \brief sets level/window to the min/max greyvalues of the given Image */ void SetAuto(const mitk::Image* image, bool tryPicTags = true, bool guessByCentralSlice = true); /** * If a level window is set to fixed, the set and get methods won't accept * modifications to the level window settings anymore. This behaviour can * be turned of by setting fixed to false; */ void SetFixed( bool fixed ); /** * Returns whether the level window settings are fixed (@see SetFixed(bool)) or not */ bool GetFixed() const; /** * Returns whether the level window settings are fixed (@see SetFixed(bool)) or not */ bool IsFixed() const; /*! * \brief equality operator implementation that allows to compare two level windows */ virtual bool operator==(const LevelWindow& levWin) const; /*! * \brief non equality operator implementation that allows to compare two level windows */ virtual bool operator!=(const LevelWindow& levWin) const; /*! * \brief implementation necessary because operator made * private in itk::Object */ virtual LevelWindow& operator=(const LevelWindow& levWin); protected: /*! * lower bound of current window */ ScalarType m_LowerWindowBound; /*! * upper bound of current window */ ScalarType m_UpperWindowBound; /*! * minimum gray value of the window */ ScalarType m_RangeMin; /*! * maximum gray value of the window */ ScalarType m_RangeMax; /*! * default minimum gray value of the window */ ScalarType m_DefaultLowerBound; /*! * default maximum gray value of the window */ ScalarType m_DefaultUpperBound; /*! * Defines whether the level window settings may be changed after * initialization or not. */ bool m_Fixed; /*! * confidence tests * * if m_LowerWindowBound > m_UpperWindowBound, then the values for m_LowerWindowBound and m_UpperWindowBound will be exchanged * * if m_LowerWindowBound < m_RangeMin, m_LowerWindowBound will be set to m_RangeMin. m_UpperWindowBound will be decreased the same as m_LowerWindowBound will be increased, but minimum value for m_UpperWindowBound is also m_RangeMin. * * if m_UpperWindowBound > m_RangeMax, m_UpperWindowBound will be set to m_RangeMax. m_LowerWindowBound will be increased the same as m_UpperWindowBound will be decreased, but maximum value for m_LowerWindowBound is also m_RangeMax. * */ inline void EnsureConsistency(); }; } // namespace mitk #endif /* LEVELWINDOW_H_HEADER_INCLUDED_C1F4F02C */ diff --git a/Core/Code/DataManagement/mitkLine.h b/Core/Code/DataManagement/mitkLine.h index 1a55b657b9..b0d76e8073 100644 --- a/Core/Code/DataManagement/mitkLine.h +++ b/Core/Code/DataManagement/mitkLine.h @@ -1,428 +1,428 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKLINE_H_HEADER_INCLUDED_C19C01E2 #define MITKLINE_H_HEADER_INCLUDED_C19C01E2 -#include "mitkVector.h" +#include "mitkTypes.h" #include #include #include #include namespace mitk { //##Documentation //## @brief Descibes a line //## @ingroup Geometry template class Line { public: Line() { m_Point.Fill(0); m_Direction.Fill(0); }; //##Documentation //## @brief Define line by point and direction //## //## Length of direction defines the the length of the line Line( const itk::Point& point, const itk::Vector& direction ) { this->m_Point = point; this->m_Direction = direction; } //##Documentation //## @brief Get start point of the line const itk::Point& GetPoint() const { return m_Point; } //##Documentation //## @brief Get start point of the line itk::Point& GetPoint() { return m_Point; } //##Documentation //## @brief Get point on the line with parameter @a t //## //## @return m_Point+t*m_Direction const itk::Point GetPoint(TCoordRep t) const { return m_Point+m_Direction*t; } //##Documentation //## @brief Set/change start point of the line void SetPoint( const itk::Point& point1 ) { itk::Vector point2; point2 = m_Point + m_Direction; m_Point = point1; m_Direction = point2 - point1; } //##Documentation //## @brief Get the direction vector of the line const itk::Vector& GetDirection() const { return m_Direction; } //##Documentation //## @brief Get the direction vector of the line itk::Vector& GetDirection() { return m_Direction; } //##Documentation //## @brief Set the direction vector of the line void SetDirection( const itk::Vector& direction ) { m_Direction = direction; } //##Documentation //## @brief Define line by point and direction //## //## Length of direction defines the the length of the line void Set( const itk::Point& point, const itk::Vector& direction ) { this->m_Point = point; this->m_Direction = direction; } //##Documentation //## @brief Define line by two points void SetPoints( const itk::Point& point1, const itk::Point& point2 ) { this->m_Point = point1; //this->m_Direction.sub( point2, point1 ); m_Direction = point2 - point1; } //##Documentation //## @brief Set/change start point of the line void SetPoint1( const itk::Point& point1 ) { itk::Vector point2; point2 = m_Point + m_Direction; m_Point = point1; m_Direction = point2 - point1; } //##Documentation //## @brief Get start point of the line const itk::Point& GetPoint1() const { return m_Point; } //##Documentation //## @brief Set/change end point of the line void SetPoint2( const itk::Point& point2 ) { m_Direction = point2 - m_Point; } //##Documentation //## @brief Get end point of the line itk::Point GetPoint2() const { itk::Point point2; point2 = m_Point+m_Direction; return point2; } //##Documentation //## @brief Transform the line with a Transform void Transform(itk::Transform& transform) { m_Direction = transform.TransformVector(m_Direction); m_Point = transform.TransformPoint(m_Point); } //##Documentation //## @brief Transform the line with a matrix //## //## Only the direction will be changed, not the start point. void Transform( const itk::Matrix& matrix ) { m_Direction = matrix*m_Direction; } //##Documentation //## @brief Distance between two lines double Distance( const Line& line ) const; //##Documentation //## @brief Distance of a point from the line double Distance( const itk::Point& point ) const { itk::Vector diff; diff = Project(point)-point; return diff.GetNorm(); } //##Documentation //## @brief Project a point on the line itk::Point Project( const itk::Point& point ) const { if(m_Direction.GetNorm()==0) return this->m_Point; itk::Vector diff; diff = point-this->m_Point; itk::Vector normalizedDirection = m_Direction; normalizedDirection.Normalize(); normalizedDirection *= dot_product(diff.GetVnlVector(), normalizedDirection.GetVnlVector()); return this->m_Point + normalizedDirection; } //##Documentation //## @brief Test if a point is part of the line //## //## Length of the direction vector defines the length of the line bool IsPartOfStraightLine( const itk::Point& point ) const { if( Distance( point ) > eps ) return false; itk::Vector diff; diff = point - this->m_Point; if( diff*m_Direction < 0 ) return false; if( diff.GetSquaredNorm() <= m_Direction.GetSquaredNorm() ) return true; return false; } //##Documentation //## @brief Test if a point is part of the line (line having infinite length) bool IsPartOfLine( const itk::Point& point ) const { if ( Distance( point ) < eps ) return true; return false; } //##Documentation //## @brief Test if a lines is parallel to this line bool IsParallel( const Line& line) const { vnl_vector normal; normal = vnl_cross_3d( m_Direction.GetVnlVector(), line.GetDirection().GetVnlVector() ); if ( normal.squared_magnitude() < eps ) return true; return false; } //##Documentation //## @brief Test if a line is part of the line (line having infinite length) bool IsPartOfLine( const Line& line ) const { return ( Distance( line.GetPoint() ) < 0 ) && ( IsParallel( line ) ); } //##Documentation //## @brief Test if the two lines are identical //## //## Start point and direction and length of direction vector must be //## equal for identical lines. bool operator==( const Line& line ) const { itk::Vector diff; diff = GetPoint1()-line.GetPoint1(); if(diff.GetSquaredNorm() > eps) return false; diff = GetPoint2()-line.GetPoint2(); if(diff.GetSquaredNorm() > eps) return false; return true; } //##Documentation //## @brief Set the line by another line inline const Line& operator=( const Line& line ) { m_Point = line.GetPoint(); m_Direction = line.GetDirection(); return *this; } //##Documentation //## @brief Test if two lines are not identical //## //## \sa operator== bool operator!=( const Line& line ) const { return !((*this)==line); } //##Documentation //## @brief Calculates the intersection points of a straight line in 2D //## with a rectangle //## //## @param x1,y1,x2,y2 rectangle //## @param p,d straight line: p point on it, d direction of line //## @param s1 first intersection point (valid only if s_num>0) //## @param s2 second intersection point (valid only if s_num==2) //## @return number of intersection points (0<=s_num<=2) static int RectangleLineIntersection( TCoordRep x1, TCoordRep y1, TCoordRep x2, TCoordRep y2, itk::Point< TCoordRep, 2 > p, itk::Vector< TCoordRep, 2 > d, itk::Point< TCoordRep, 2 > &s1, itk::Point< TCoordRep, 2 > &s2 ) { int s_num; TCoordRep t; s_num=0; /*test if intersecting with the horizontal axis*/ if(fabs(d[0])>eps) { t=(x1-p[0])/d[0]; itk::Point l=p+d*t; if((l[1]>=y1) && (l[1]eps) { t=(x2-p[0])/d[0]; itk::Point l=p+d*t; if((l[1]>=y1) && (l[1]eps) { t=(y1-p[1])/d[1]; itk::Point l=p+d*t; if((l[0]>=x1) && (l[0]eps) { t=(y2-p[1])/d[1]; itk::Point l=p+d*t; if((l[0]>=x1) && (l[0]0) * \param s2 second intersection point (valid only if s_num==2) * \return number of intersection points (0<=s_num<=2) */ static int BoxLineIntersection( TCoordRep x1, TCoordRep y1, TCoordRep z1, TCoordRep x2, TCoordRep y2, TCoordRep z2, itk::Point< TCoordRep, 3 > p, itk::Vector< TCoordRep, 3 > d, itk::Point< TCoordRep, 3 > &s1, itk::Point< TCoordRep, 3 > &s2 ) { int num = 0; ScalarType box[6]; box[0] = x1; box[1] = x2; box[2] = y1; box[3] = y2; box[4] = z1; box[5] = z2; itk::Point< TCoordRep, 3 > point; int i, j; for ( i = 0; i < 6; ++i ) { j = i / 2; if ( fabs( d[j] ) > eps ) { ScalarType lambda = (box[i] - p[j]) / d[j]; point = p + d * lambda; int k = (j + 1) % 3; int l = (j + 2) % 3; if ( (point[k] >= box[k*2]) && (point[k] <= box[k*2+1]) && (point[l] >= box[l*2]) && (point[l] <= box[l*2+1]) ) { if ( num == 0 ) { s1 = point; } else { s2 = point; } ++num; } } } return num; } protected: itk::Point m_Point; itk::Vector m_Direction; }; typedef Line Line3D; } // namespace mitk #endif /* MITKLINE_H_HEADER_INCLUDED_C19C01E2 */ diff --git a/Core/Code/DataManagement/mitkPlaneOperation.h b/Core/Code/DataManagement/mitkPlaneOperation.h index 505a438ded..243fd647aa 100644 --- a/Core/Code/DataManagement/mitkPlaneOperation.h +++ b/Core/Code/DataManagement/mitkPlaneOperation.h @@ -1,60 +1,60 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKPlaneOperation_H #define MITKPlaneOperation_H #include #include "mitkPointOperation.h" -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { /** * @brief Operation for setting a plane (defined by its origin and normal) * * @ingroup Undo */ class MITK_CORE_EXPORT PlaneOperation : public PointOperation { public: PlaneOperation( OperationType operationType, Point3D point, Vector3D normal ); PlaneOperation( OperationType operationType, Point3D point, Vector3D axisVec0, Vector3D axisVec1 ); virtual ~PlaneOperation(); Vector3D GetNormal(); Vector3D GetAxisVec0(); Vector3D GetAxisVec1(); bool AreAxisDefined(); private: Vector3D m_Normal; Vector3D m_AxisVec0; Vector3D m_AxisVec1; bool m_AreAxisDefined; }; } //namespace mitk #endif /* MITKPlaneOperation_H */ diff --git a/Core/Code/DataManagement/mitkPointOperation.h b/Core/Code/DataManagement/mitkPointOperation.h index d8f5939f1f..ca8b84298c 100755 --- a/Core/Code/DataManagement/mitkPointOperation.h +++ b/Core/Code/DataManagement/mitkPointOperation.h @@ -1,84 +1,84 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKPOINTOPERATION_H #define MITKPOINTOPERATION_H #include #include "mitkOperation.h" -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { //##Documentation //## @brief Operation that handles all actions on one Point. //## //## Stores everything for Adding, Moving and Deleting a Point. //## @ingroup Undo class MITK_CORE_EXPORT PointOperation : public Operation { public: //##Documentation //##@brief Operation that handles all actions on one Point. //## //## @param operationType is the type of the operation (see mitkOperation.h; e.g. move or add; Information for StateMachine::ExecuteOperation()); //## @param point is the information of the point to add or is the information to change a point into //## @param index is e.g. the position in a list which describes the element to change PointOperation(OperationType operationType, Point3D point, int index = -1, bool selected = true, PointSpecificationType type = PTUNDEFINED); //##Documentation //##@brief Operation that handles all actions on one Point. //## //## @param operationType is the type of the operation (see mitkOperation.h; e.g. move or add; Information for StateMachine::ExecuteOperation()); //## @param point is the information of the point to add or is the information to change a point into //## @param index is e.g. the position in a list which describes the element to change PointOperation(OperationType operationType, ScalarType timeInMS, Point3D point, int index = -1, bool selected = true, PointSpecificationType type = PTUNDEFINED); virtual ~PointOperation(); Point3D GetPoint(); int GetIndex(); bool GetSelected(); PointSpecificationType GetPointType(); ScalarType GetTimeInMS() const; private: Point3D m_Point; //##Documentation //##@brief to declare an index where to store the point in data int m_Index; //to declare weather the point is selected or deselected bool m_Selected; //##Documentation //##@brief to describe the type of the point. See enum PointSpecification for different types PointSpecificationType m_Type; ScalarType m_TimeInMS; }; }//namespace mitk #endif /* MITKPOINTOPERATION_H*/ diff --git a/Core/Code/DataManagement/mitkProperties.h b/Core/Code/DataManagement/mitkProperties.h index c6fc2aa1ee..063b6580b7 100644 --- a/Core/Code/DataManagement/mitkProperties.h +++ b/Core/Code/DataManagement/mitkProperties.h @@ -1,52 +1,52 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKPROPERTIES_H_HEADER_INCLUDED #define MITKPROPERTIES_H_HEADER_INCLUDED #include "mitkGenericProperty.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkLookupTables.h" namespace mitk { mitkDeclareGenericProperty(BoolProperty,bool,MITK_CORE_EXPORT); mitkDeclareGenericProperty(IntProperty,int,MITK_CORE_EXPORT); mitkDeclareGenericProperty(FloatProperty,float,MITK_CORE_EXPORT); mitkDeclareGenericProperty(DoubleProperty,double,MITK_CORE_EXPORT); mitkDeclareGenericProperty(Vector3DProperty,Vector3D,MITK_CORE_EXPORT); mitkDeclareGenericProperty(Point3dProperty,Point3D,MITK_CORE_EXPORT); mitkDeclareGenericProperty(Point4dProperty,Point4D,MITK_CORE_EXPORT); mitkDeclareGenericProperty(Point3iProperty,Point3I,MITK_CORE_EXPORT); mitkDeclareGenericProperty(FloatLookupTableProperty, FloatLookupTable,MITK_CORE_EXPORT); mitkDeclareGenericProperty(BoolLookupTableProperty, BoolLookupTable,MITK_CORE_EXPORT); mitkDeclareGenericProperty(IntLookupTableProperty, IntLookupTable,MITK_CORE_EXPORT); mitkDeclareGenericProperty(StringLookupTableProperty, StringLookupTable,MITK_CORE_EXPORT); /** * \warning If you add more specialization of GenericProperty, you must also add these to the * templated GetPropertyValue() method in mitkPropertyList.cpp! */ } // namespace mitk #endif /* MITKPROPERTIES_H_HEADER_INCLUDED */ diff --git a/Core/Code/DataManagement/mitkPropertyList.cpp b/Core/Code/DataManagement/mitkPropertyList.cpp index 94278f7332..2472dac695 100644 --- a/Core/Code/DataManagement/mitkPropertyList.cpp +++ b/Core/Code/DataManagement/mitkPropertyList.cpp @@ -1,284 +1,284 @@ /*=================================================================== 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 "mitkPropertyList.h" #include "mitkProperties.h" #include "mitkStringProperty.h" -#include "mitkVector.h" +#include "mitkTypes.h" mitk::BaseProperty* mitk::PropertyList::GetProperty(const std::string& propertyKey) const { PropertyMap::const_iterator it; it=m_Properties.find( propertyKey ); if(it!=m_Properties.end()) return it->second; else return NULL; } void mitk::PropertyList::SetProperty(const std::string& propertyKey, BaseProperty* property) { if (!property) return; //make sure that BaseProperty*, which may have just been created and never been //assigned to a SmartPointer, is registered/unregistered properly. If we do not //do that, it will a) not deleted in case it is identical to the old one or //b) possibly deleted when temporarily added to a smartpointer somewhere below. BaseProperty::Pointer tmpSmartPointerToProperty = property; PropertyMap::iterator it( m_Properties.find( propertyKey ) ); // Is a property with key @a propertyKey contained in the list? if( it != m_Properties.end() ) { // yes //is the property contained in the list identical to the new one? if( it->second->operator==(*property) ) { // yes? do nothing and return. return; } if (it->second->AssignProperty(*property)) { // The assignment was successfull this->Modified(); } else { MITK_ERROR << "In " __FILE__ ", l." << __LINE__ << ": Trying to set existing property " << it->first << " of type " << it->second->GetNameOfClass() << " to a property with different type " << property->GetNameOfClass() << "." << " Use ReplaceProperty() instead." << std::endl; } return; } //no? add it. PropertyMapElementType newProp; newProp.first = propertyKey; newProp.second = property; m_Properties.insert ( newProp ); this->Modified(); } void mitk::PropertyList::ReplaceProperty(const std::string& propertyKey, BaseProperty* property) { if (!property) return; PropertyMap::iterator it( m_Properties.find( propertyKey ) ); // Is a property with key @a propertyKey contained in the list? if( it != m_Properties.end() ) { it->second=NULL; m_Properties.erase(it); } //no? add/replace it. PropertyMapElementType newProp; newProp.first = propertyKey; newProp.second = property; m_Properties.insert ( newProp ); Modified(); } mitk::PropertyList::PropertyList() { } mitk::PropertyList::PropertyList(const mitk::PropertyList& other) : itk::Object() { for (PropertyMap::const_iterator i = other.m_Properties.begin(); i != other.m_Properties.end(); ++i) { m_Properties.insert(std::make_pair(i->first, i->second->Clone())); } } mitk::PropertyList::~PropertyList() { Clear(); } /** * Consider the list as changed when any of the properties has changed recently. */ unsigned long mitk::PropertyList::GetMTime() const { for ( PropertyMap::const_iterator it = m_Properties.begin() ; it != m_Properties.end(); ++it ) { if( it->second.IsNull() ) { itkWarningMacro(<< "Property '" << it->first <<"' contains nothing (NULL)."); continue; } if( Superclass::GetMTime() < it->second->GetMTime() ) { Modified(); break; } } return Superclass::GetMTime(); } bool mitk::PropertyList::DeleteProperty(const std::string& propertyKey) { PropertyMap::iterator it; it=m_Properties.find( propertyKey ); if(it!=m_Properties.end()) { it->second=NULL; m_Properties.erase(it); Modified(); return true; } return false; } void mitk::PropertyList::Clear() { PropertyMap::iterator it = m_Properties.begin(), end = m_Properties.end(); while(it!=end) { it->second = NULL; ++it; } m_Properties.clear(); } itk::LightObject::Pointer mitk::PropertyList::InternalClone() const { itk::LightObject::Pointer result(new Self(*this)); return result; } void mitk::PropertyList::ConcatenatePropertyList(PropertyList *pList, bool replace) { if (pList) { const PropertyMap* propertyMap = pList->GetMap(); for ( PropertyMap::const_iterator iter = propertyMap->begin(); // m_PropertyList is created in the constructor, so we don't check it here iter != propertyMap->end(); ++iter ) { const std::string key = iter->first; BaseProperty* value = iter->second; if (replace) { ReplaceProperty( key.c_str(), value ); } else { SetProperty( key.c_str(), value ); } } } } bool mitk::PropertyList::GetBoolProperty(const char* propertyKey, bool& boolValue) const { BoolProperty *gp = dynamic_cast( GetProperty(propertyKey) ); if ( gp != NULL ) { boolValue = gp->GetValue(); return true; } return false; // Templated Method does not work on Macs //return GetPropertyValue(propertyKey, boolValue); } bool mitk::PropertyList::GetIntProperty(const char* propertyKey, int &intValue) const { IntProperty *gp = dynamic_cast( GetProperty(propertyKey) ); if ( gp != NULL ) { intValue = gp->GetValue(); return true; } return false; // Templated Method does not work on Macs //return GetPropertyValue(propertyKey, intValue); } bool mitk::PropertyList::GetFloatProperty(const char* propertyKey, float &floatValue) const { FloatProperty *gp = dynamic_cast( GetProperty(propertyKey) ); if ( gp != NULL ) { floatValue = gp->GetValue(); return true; } return false; // Templated Method does not work on Macs //return GetPropertyValue(propertyKey, floatValue); } bool mitk::PropertyList::GetStringProperty(const char* propertyKey, std::string& stringValue) const { StringProperty* sp= dynamic_cast(GetProperty(propertyKey)); if ( sp != NULL ) { stringValue = sp->GetValue(); return true; } return false; } void mitk::PropertyList::SetIntProperty(const char* propertyKey, int intValue) { SetProperty(propertyKey, mitk::IntProperty::New(intValue)); } void mitk::PropertyList::SetBoolProperty( const char* propertyKey, bool boolValue) { SetProperty(propertyKey, mitk::BoolProperty::New(boolValue)); } void mitk::PropertyList::SetFloatProperty( const char* propertyKey, float floatValue) { SetProperty(propertyKey, mitk::FloatProperty::New(floatValue)); } void mitk::PropertyList::SetStringProperty( const char* propertyKey, const char* stringValue) { SetProperty(propertyKey, mitk::StringProperty::New(stringValue)); } diff --git a/Core/Code/DataManagement/mitkRestorePlanePositionOperation.h b/Core/Code/DataManagement/mitkRestorePlanePositionOperation.h index 12116b6cd7..5f3babde85 100644 --- a/Core/Code/DataManagement/mitkRestorePlanePositionOperation.h +++ b/Core/Code/DataManagement/mitkRestorePlanePositionOperation.h @@ -1,76 +1,76 @@ /*=================================================================== 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. ===================================================================*/ #ifndef mitkRestorePlanePositionOperation_h_Included #define mitkRestorePlanePositionOperation_h_Included #include "mitkCommon.h" #include "mitkPointOperation.h" -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { //##Documentation //## TODO class MITK_CORE_EXPORT RestorePlanePositionOperation : public Operation { public: //##Documentation //##@brief Operation that handles all actions on one Point. //## //## @param operationType is the type of the operation (see mitkOperation.h; e.g. move or add; Information for StateMachine::ExecuteOperation()); //## @param point is the information of the point to add or is the information to change a point into //## @param index is e.g. the position in a list which describes the element to change //PointOperation(OperationType operationType, Point3D point, int index = -1, bool selected = true, PointSpecificationType type = PTUNDEFINED); RestorePlanePositionOperation(OperationType operationType, float width, float height, Vector3D spacing, unsigned int pos, Vector3D direction, AffineTransform3D::Pointer transform); virtual ~RestorePlanePositionOperation(); Vector3D GetDirectionVector(); float GetWidth(); float GetHeight(); Vector3D GetSpacing(); unsigned int GetPos(); AffineTransform3D::Pointer GetTransform(); private: Vector3D m_Spacing; Vector3D m_DirectionVector; float m_Width; float m_Height; unsigned int m_Pos; AffineTransform3D::Pointer m_Transform; }; }//namespace mitk #endif diff --git a/Core/Code/DataManagement/mitkRotationOperation.h b/Core/Code/DataManagement/mitkRotationOperation.h index 5301d45214..ae8f9cabd7 100644 --- a/Core/Code/DataManagement/mitkRotationOperation.h +++ b/Core/Code/DataManagement/mitkRotationOperation.h @@ -1,47 +1,47 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKROTATIONOPERATION_H_HEADER_INCLUDED #define MITKROTATIONOPERATION_H_HEADER_INCLUDED #include "mitkOperation.h" -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { //##Documentation //## @brief Operation, that holds everything necessary for an rotation operation //## //## @ingroup Undo class MITK_CORE_EXPORT RotationOperation : public Operation { public: RotationOperation(OperationType operationType, Point3D pointOfRotation, Vector3D vectorOfRotation, ScalarType angleOfRotation); virtual ~RotationOperation(void); virtual ScalarType GetAngleOfRotation(); virtual const Point3D GetCenterOfRotation(); virtual const Vector3D GetVectorOfRotation(); protected: ScalarType m_AngleOfRotation; Point3D m_PointOfRotation; Vector3D m_VectorOfRotation; }; } // namespace mitk #endif /* MITKROTATIONOPERATION_H_HEADER_INCLUDED */ diff --git a/Core/Code/DataManagement/mitkVector.h b/Core/Code/DataManagement/mitkTypes.h similarity index 100% copy from Core/Code/DataManagement/mitkVector.h copy to Core/Code/DataManagement/mitkTypes.h diff --git a/Core/Code/DataManagement/mitkVector.cpp b/Core/Code/DataManagement/mitkVector.cpp index 9359e39422..c93967221f 100644 --- a/Core/Code/DataManagement/mitkVector.cpp +++ b/Core/Code/DataManagement/mitkVector.cpp @@ -1,17 +1,17 @@ /*=================================================================== 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 "mitkVector.h" +#include "mitkTypes.h" diff --git a/Core/Code/DataManagement/mitkVector.h b/Core/Code/DataManagement/mitkVector.h index 8ef89b1a25..11edb5f7f7 100644 --- a/Core/Code/DataManagement/mitkVector.h +++ b/Core/Code/DataManagement/mitkVector.h @@ -1,485 +1,23 @@ /*=================================================================== 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. ===================================================================*/ +#ifndef MITKVECTOR_H_ +#define MITKVECTOR_H_ -#ifndef MITKVECTOR_H_HEADER_INCLUDED_C1EBD0AD -#define MITKVECTOR_H_HEADER_INCLUDED_C1EBD0AD -// this is needed for memcopy in ITK -// can be removed when fixed in ITK -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "mitkPoint.h" // TODO SW: should not be included here, maybe generate one "general datatype include" like mitkPrimitives.h -#include "mitkDataTypeBasics.h" -#ifndef DOXYGEN_SKIP - -namespace mitk { - - -typedef itk::Matrix Matrix3D; -typedef itk::Matrix Matrix4D; -typedef vnl_matrix_fixed VnlMatrix3D; -typedef itk::Transform Transform3D; -typedef vnl_vector VnlVector; -typedef vnl_vector_ref VnlVectorRef; - - - - - -typedef itk::Vector Vector2D; -typedef itk::Vector Vector3D; -typedef itk::Index<3> Index3D; -typedef itk::ContinuousIndex ContinuousIndex3D; -typedef vnl_quaternion Quaternion; - -//##Documentation -//##@brief enumeration of the type a point can be -enum PointSpecificationType -{ - PTUNDEFINED = 0, - PTSTART, - PTCORNER, - PTEDGE, - PTEND -}; - -typedef itk::NumericTraits ScalarTypeNumericTraits; -MITK_CORE_EXPORT extern const ScalarType eps; -MITK_CORE_EXPORT extern const ScalarType sqrteps; -MITK_CORE_EXPORT extern const double large; - -template class VectorTraits { - public: - typedef T ValueType; -}; - -template <> class VectorTraits { - public: - typedef ScalarType ValueType; -}; - -template<> class VectorTraits { - public: - typedef float ValueType; -}; - -template<> class VectorTraits< itk::Index<5> > { - public: - typedef itk::Index<5>::IndexValueType ValueType; -}; - -template<> class VectorTraits< itk::Index<3> > { - public: - typedef itk::Index<3>::IndexValueType ValueType; -}; - -template<> class VectorTraits< long int [3]> { - public: - typedef long int ValueType; -}; -template<> class VectorTraits< float [3]> { - public: - typedef float ValueType; -}; -template<> class VectorTraits< double [3]> { - public: - typedef double ValueType; -}; - -template<> class VectorTraits< vnl_vector_fixed > { - public: - typedef ScalarType ValueType; -}; - -template<> class VectorTraits< long unsigned int[3]> { - public: - typedef long unsigned int ValueType; -}; - -template<> class VectorTraits< unsigned int *> { - public: - typedef unsigned int ValueType; -}; - -template<> class VectorTraits< double[4] > { - public: - typedef double ValueType; -}; - -template<> class VectorTraits< itk::Vector > { - public: - typedef float ValueType; -}; - -template<> class VectorTraits< mitk::Point > { - public: - typedef float ValueType; -}; - -template<> class VectorTraits< mitk::Point > { - public: - typedef float ValueType; -}; - - -template<> class VectorTraits< itk::Point > { - public: - typedef float ValueType; -}; - -template<> class VectorTraits< itk::Point > { - public: - typedef float ValueType; -}; - -template<> class VectorTraits< itk::Vector > { - public: - typedef double ValueType; -}; - -template<> class VectorTraits< mitk::Point > { - public: - typedef double ValueType; -}; - -template<> class VectorTraits< mitk::Point > { -public: - typedef double ValueType; -}; - -template<> class VectorTraits< itk::Point > { - public: - typedef double ValueType; -}; - -template<> class VectorTraits< itk::Point > { -public: - typedef double ValueType; -}; - - -template<> class VectorTraits< itk::Vector > { - public: - typedef int ValueType; -}; - -template<> class VectorTraits< mitk::Point > { - public: - typedef int ValueType; -}; - -template - inline void itk2vtk(const Tin& in, Tout& out) -{ - out[0]=(typename VectorTraits::ValueType)(in[0]); - out[1]=(typename VectorTraits::ValueType)(in[1]); - out[2]=(typename VectorTraits::ValueType)(in[2]); -} - -template - inline void vtk2itk(const Tin& in, Tout& out) -{ - out[0]=(typename VectorTraits::ValueType)(in[0]); - out[1]=(typename VectorTraits::ValueType)(in[1]); - out[2]=(typename VectorTraits::ValueType)(in[2]); -} -template - inline void FillVector3D(Tout& out, ScalarType x, ScalarType y, ScalarType z) -{ - out[0] = (typename VectorTraits::ValueType)x; - out[1] = (typename VectorTraits::ValueType)y; - out[2] = (typename VectorTraits::ValueType)z; -} -template - inline void FillVector4D(Tout& out, ScalarType x, ScalarType y, ScalarType z, ScalarType t) -{ - out[0] = (typename VectorTraits::ValueType)x; - out[1] = (typename VectorTraits::ValueType)y; - out[2] = (typename VectorTraits::ValueType)z; - out[3] = (typename VectorTraits::ValueType)t; -} - - -template - inline void vnl2vtk(const vnl_vector& in, Tout *out) -{ - unsigned int i; - for(i=0; i - inline void vtk2vnl(const Tin *in, vnl_vector& out) -{ - unsigned int i; - for(i=0; i - inline void vtk2vnlref(const Tin *in, vnl_vector_ref& out) -{ - unsigned int i; - for(i=0; i - inline void vnl2vtk(const vnl_vector_fixed& in, Tout *out) -{ - unsigned int i; - for(i=0; i - inline void vtk2vnl(const Tin *in, vnl_vector_fixed& out) -{ - unsigned int i; - for(i=0; i - itk::Vector operator+(const itk::Vector &vector, const itk::Point &point) -{ - itk::Vector sub; - for( unsigned int i=0; i - inline itk::Vector& operator+=(itk::Vector &vector, const itk::Point &point) -{ - for( unsigned int i=0; i - itk::Vector operator-(const itk::Vector &vector, const itk::Point &point) -{ - itk::Vector sub; - for( unsigned int i=0; i - inline itk::Vector& operator-=(itk::Vector &vector, const itk::Point &point) -{ - for( unsigned int i=0; i -inline bool MatrixEqualRMS(const vnl_matrix_fixed& matrix1,const vnl_matrix_fixed& matrix2,mitk::ScalarType epsilon=mitk::eps) -{ - if ( (matrix1.rows() == matrix2.rows()) && (matrix1.cols() == matrix2.cols()) ) - { - vnl_matrix_fixed differenceMatrix = matrix1-matrix2; - if (differenceMatrix.rms() -inline bool MatrixEqualRMS(const itk::Matrix& matrix1,const itk::Matrix& matrix2,mitk::ScalarType epsilon=mitk::eps) -{ - return mitk::MatrixEqualRMS(matrix1.GetVnlMatrix(),matrix2.GetVnlMatrix(),epsilon); -} - -/*! -\brief Check for element-wise matrix equality with a user defined accuracy. -\param matrix1 first vnl matrix -\param matrix2 second vnl matrix -\param epsilon user defined accuracy bounds -*/ -template -inline bool MatrixEqualElementWise(const vnl_matrix_fixed& matrix1,const vnl_matrix_fixed& matrix2,mitk::ScalarType epsilon=mitk::eps) -{ - if ( (matrix1.rows() == matrix2.rows()) && (matrix1.cols() == matrix2.cols()) ) - { - for( unsigned int r=0; repsilon) - { - return false; - } - } - } - return true; - } - else - { - return false; - } -} - -/*! -\brief Check for element-wise matrix equality with a user defined accuracy. -\param matrix1 first itk matrix -\param matrix2 second itk matrix -\param epsilon user defined accuracy bounds -*/ -template -inline bool MatrixEqualElementWise(const itk::Matrix& matrix1,const itk::Matrix& matrix2,mitk::ScalarType epsilon=mitk::eps) -{ - return mitk::MatrixEqualElementWise(matrix1.GetVnlMatrix(),matrix2.GetVnlMatrix(),epsilon); -} - -template -inline bool Equal(const itk::Vector& vector1, const itk::Vector& vector2, TCoordRep eps=mitk::eps) -{ - typename itk::Vector::VectorType diff = vector1-vector2; - for (unsigned int i=0; ieps || diff[i]<-eps) - return false; - return true; -} - -template - inline bool Equal(const itk::Point& vector1, const itk::Point& vector2, TCoordRep eps=mitk::eps) -{ - typename itk::Point::VectorType diff = vector1-vector2; - for (unsigned int i=0; ieps || diff[i]<-eps) - return false; - return true; -} - -inline bool Equal(const mitk::VnlVector& vector1, const mitk::VnlVector& vector2, ScalarType eps=mitk::eps) -{ - mitk::VnlVector diff = vector1-vector2; - for (unsigned int i=0; ieps || diff[i]<-eps) - return false; - return true; -} - -inline bool Equal(ScalarType scalar1, ScalarType scalar2, ScalarType eps=mitk::eps) -{ - return fabs(scalar1-scalar2) < eps; -} - -template - inline bool Equal(const vnl_vector_fixed & vector1, const vnl_vector_fixed& vector2, TCoordRep eps=mitk::eps) -{ - vnl_vector_fixed diff = vector1-vector2; - bool returnValue = true; - for( unsigned int i=0; ieps || diff[i]<-eps) - { - returnValue = false; - } - } - - return returnValue; -} - -template -inline void TransferMatrix(const itk::Matrix& in, itk::Matrix& out) -{ - for (unsigned int i = 0; i < in.RowDimensions; ++i) - for (unsigned int j = 0; j < in.ColumnDimensions; ++j) - out[i][j] = in[i][j]; -} - - -} // namespace mitk - -#endif //DOXYGEN_SKIP - -/* - * This part of the code has been shifted here to avoid compiler clashes - * caused by including before the declaration of - * the Equal() methods above. This problem occurs when using MSVC and is - * probably related to a compiler bug. - */ - -#include - -namespace mitk -{ - typedef itk::AffineGeometryFrame::TransformType AffineTransform3D; -} - - -#define mitkSetConstReferenceMacro(name,type) \ - virtual void Set##name (const type & _arg) \ - { \ - itkDebugMacro("setting " << #name " to " << _arg ); \ - if (this->m_##name != _arg) \ - { \ - this->m_##name = _arg; \ - this->Modified(); \ - } \ - } - -#define mitkSetVectorMacro(name,type) \ - mitkSetConstReferenceMacro(name,type) - -#define mitkGetVectorMacro(name,type) \ - itkGetConstReferenceMacro(name,type) - -#endif /* MITKVECTOR_H_HEADER_INCLUDED_C1EBD0AD */ +#endif /* MITKVECTOR_H_ */ diff --git a/Core/Code/Interactions/mitkAffineInteractor.h b/Core/Code/Interactions/mitkAffineInteractor.h index b7dd151ee8..a9f9e12245 100755 --- a/Core/Code/Interactions/mitkAffineInteractor.h +++ b/Core/Code/Interactions/mitkAffineInteractor.h @@ -1,83 +1,83 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKAFFINEINTERACTOR_H_HEADER_INCLUDED_C188C29F #define MITKAFFINEINTERACTOR_H_HEADER_INCLUDED_C188C29F #include #include "mitkInteractor.h" -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { class DisplayPositionEvent; //##Documentation //## @brief Interactor for Affine transformations translate, rotate and scale //## //## An object of this class can translate, rotate and scale the data objects //## by modifying its geometry. //## @ingroup Interaction //create events for interactions #pragma GCC visibility push(default) itkEventMacro(AffineInteractionEvent, itk::AnyEvent); itkEventMacro(ScaleEvent, AffineInteractionEvent); itkEventMacro(RotateEvent, AffineInteractionEvent); itkEventMacro(TranslateEvent, AffineInteractionEvent); #pragma GCC visibility pop class MITK_CORE_EXPORT AffineInteractor : public Interactor { public: mitkClassMacro(AffineInteractor,Interactor); // itkNewMacro(Self); mitkNewMacro2Param(Self, const char*, DataNode*); protected: // AffineInteractor(); //obsolete //##Documentation //## @brief Constructor //## //## @param dataNode is the node, this Interactor is connected to //## @param type is the type of StateMachine like declared in the XML-Configure-File AffineInteractor(const char * type, DataNode* dataNode); //##Documentation //## @brief Destructor ~AffineInteractor(){}; virtual bool ExecuteAction(Action* action, mitk::StateEvent const* stateEvent); //##Documentation //## @brief calculates how good the data this state machine handles is hit by the event. //## //## Returns a value between 0 and 1. //## (Used by GlobalInteraction to decide which DESELECTED state machine to send the event to.) //## //## \WARNING This is interactor currently does not work for interaction in 3D. Try using mitkAffineInteractor3D instead. virtual float CanHandleEvent(StateEvent const* stateEvent) const; bool CheckSelected(const mitk::Point3D& worldPoint, int timestep); bool ConvertDisplayEventToWorldPosition(mitk::DisplayPositionEvent const* displayEvent, mitk::Point3D& worldPoint); mitk::Point3D m_LastMousePosition; }; } // namespace mitk #endif /* MITKAFFINEINTERACTOR_H_HEADER_INCLUDED_C188C29F */ diff --git a/Core/Code/Interactions/mitkCoordinateSupplier.h b/Core/Code/Interactions/mitkCoordinateSupplier.h index 44f0628533..9a69b0b08b 100755 --- a/Core/Code/Interactions/mitkCoordinateSupplier.h +++ b/Core/Code/Interactions/mitkCoordinateSupplier.h @@ -1,65 +1,65 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKCOORDINATESUPPLIER_H #define MITKCOORDINATESUPPLIER_H #include #include "mitkStateMachine.h" -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { class Operation; class OperationActor; //##Documentation //## @brief Interactor //## //## sends a Point, that can be processed in its own OperationActor //## @ingroup Interaction class MITK_CORE_EXPORT CoordinateSupplier : public StateMachine { public: mitkClassMacro(CoordinateSupplier, StateMachine); mitkNewMacro2Param(Self, const char*, OperationActor*); itkGetConstReferenceMacro(CurrentPoint, Point3D); protected: //##Documentation //## @brief Constructor with needed arguments //## @param type: string, that describes the StateMachine-Scheme to take from all SM (see XML-File) //## @param operationActor: the Data, operations (+ points) are send to CoordinateSupplier(const char * type, OperationActor* operationActor); ~CoordinateSupplier(); //##Documentation //## @brief executes the actions that are sent to this statemachine //## derived from StateMachine virtual bool ExecuteAction(Action* action, mitk::StateEvent const* stateEvent); private: OperationActor* m_Destination; Point3D m_OldPoint; Point3D m_CurrentPoint; }; } // namespace mitk #endif /* MITKCOORDINATESUPPLIER_H */ diff --git a/Core/Code/Interactions/mitkDisplayCoordinateOperation.h b/Core/Code/Interactions/mitkDisplayCoordinateOperation.h index 62b1ffb68e..32fac53c69 100644 --- a/Core/Code/Interactions/mitkDisplayCoordinateOperation.h +++ b/Core/Code/Interactions/mitkDisplayCoordinateOperation.h @@ -1,84 +1,84 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKDISPLAYCOORDINATEOPERATION_H_HEADER_INCLUDED_C10E33D0 #define MITKDISPLAYCOORDINATEOPERATION_H_HEADER_INCLUDED_C10E33D0 #include #include "mitkBaseRenderer.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkOperation.h" #include #define mitkGetMacro(name,type) \ virtual type Get##name () \ { \ return this->m_##name; \ } namespace mitk { // TODO Legacy , no longer necessary when after migrating all DisplayInteractions to new Interactions. // Coordinate supplier can probably also be removed then. //##Documentation //## @brief Operation with informations necessary for operations of DisplayVectorInteractor //## @ingroup Undo class MITK_CORE_EXPORT DisplayCoordinateOperation : public Operation { public: DisplayCoordinateOperation(mitk::OperationType operationType, mitk::BaseRenderer* renderer, const mitk::Point2D& startDisplayCoordinate, const mitk::Point2D& lastDisplayCoordinate, const mitk::Point2D& currentDisplayCoordinate ); DisplayCoordinateOperation(mitk::OperationType operationType, mitk::BaseRenderer* renderer, const mitk::Point2D& startDisplayCoordinate, const mitk::Point2D& lastDisplayCoordinate, const mitk::Point2D& currentDisplayCoordinate, const mitk::Point2D& startCoordinateInMM ); virtual ~DisplayCoordinateOperation(); mitk::BaseRenderer* GetRenderer(); mitkGetMacro(StartDisplayCoordinate, mitk::Point2D); mitkGetMacro(LastDisplayCoordinate, mitk::Point2D); mitkGetMacro(CurrentDisplayCoordinate, mitk::Point2D); mitkGetMacro(StartCoordinateInMM, mitk::Point2D); mitk::Vector2D GetLastToCurrentDisplayVector(); mitk::Vector2D GetStartToCurrentDisplayVector(); mitk::Vector2D GetStartToLastDisplayVector(); private: mitk::WeakPointer< mitk::BaseRenderer > m_Renderer; const mitk::Point2D m_StartDisplayCoordinate; const mitk::Point2D m_LastDisplayCoordinate; const mitk::Point2D m_CurrentDisplayCoordinate; const mitk::Point2D m_StartCoordinateInMM; }; } #endif /* MITKDISPLAYCOORDINATEOPERATION_H_HEADER_INCLUDED_C10E33D0 */ diff --git a/Core/Code/Interactions/mitkDisplayPositionEvent.h b/Core/Code/Interactions/mitkDisplayPositionEvent.h index f3ed4377a3..1dd8968f88 100644 --- a/Core/Code/Interactions/mitkDisplayPositionEvent.h +++ b/Core/Code/Interactions/mitkDisplayPositionEvent.h @@ -1,82 +1,82 @@ /*=================================================================== 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. ===================================================================*/ #ifndef DISPLAYPOSITIONEVENT_H_HEADER_INCLUDED_C184F366 #define DISPLAYPOSITIONEVENT_H_HEADER_INCLUDED_C184F366 #include #include "mitkEvent.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkDataNode.h" namespace mitk { /** * \brief Event that stores coordinates * * Stores display position of the mouse. * * If requested, the correspondent 3D world position in mm is calculated via * picking (delegated to the BaseRenderer). Additionally, the mitk::BaseData or * mitk::DataNode corresponding to the picked object in the (3D) scene can * be retrieved. * \ingroup Interaction * \deprecatedSince{2013_03} mitk::DisplayPositionEvent is deprecated. Use mitk::InteractionPositionEvent instead. * Refer to \see DataInteractionPage for general information about the concept of the new implementation. */ class MITK_CORE_EXPORT DisplayPositionEvent : public Event { public: /** \brief Constructor with all necessary arguments. * * \param sender is the renderer that caused that event * \param type, button, buttonState, key: information from the Event * \param displPosition is the 2D Position of the mouse */ DisplayPositionEvent(BaseRenderer* sender, int type, int button, int buttonState, int key, const Point2D& displPosition); const Point2D& GetDisplayPosition() const { return m_DisplayPosition; } void SetDisplayPosition(const Point2D& displPosition) { m_DisplayPosition = displPosition; } Point3D& GetWorldPosition() const; /** Returns node with object at the current position (NULL if not applicable) */ mitk::DataNode *GetPickedObjectNode() const; /** Returns object at the current position (NULL if not applicable) */ mitk::BaseData *GetPickedObject() const; protected: Point2D m_DisplayPosition; mutable Point3D m_WorldPosition; mutable bool m_WorldPositionIsSet; mutable mitk::DataNode::Pointer m_PickedObjectNode; mutable bool m_PickedObjectIsSet; }; typedef DisplayPositionEvent MouseEvent; } // namespace mitk #endif /* DISPLAYPOSITIONozsiEVENT_H_HEADER_INCLUDED_C184F366 */ diff --git a/Core/Code/Interactions/mitkKeyEvent.h b/Core/Code/Interactions/mitkKeyEvent.h index 6f4f555edb..ffb0df9c37 100644 --- a/Core/Code/Interactions/mitkKeyEvent.h +++ b/Core/Code/Interactions/mitkKeyEvent.h @@ -1,83 +1,83 @@ /*=================================================================== 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. ===================================================================*/ #ifndef KeyEvent_H_HEADER_INCLUDED_C184F366 #define KeyEvent_H_HEADER_INCLUDED_C184F366 #include #include "mitkEvent.h" -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { //##Documentation //## @brief Event that stores coordinates and the key which is pressed //## //## Stores display position of the mouse. If requested, the correspondent //## 3D world position in mm is calculated via picking (delegated to the //## BaseRenderer). //## @ingroup Interaction /** * \deprecatedSince{2013_03} KeyEvent is deprecated. Use mitk::InteractionKeyEvent instead. * Refer to \see DataInteractionPage for general information about the concept of the new implementation. */ class MITK_CORE_EXPORT KeyEvent : public Event { public: //##Documentation //## @brief Constructor with all necessary arguments. //## //## @param sender is the renderer that caused that event //## @param type, button, buttonState, key: information from the Event //## @param displPosition is the 2D Position of the mouse KeyEvent(BaseRenderer* sender, int type, int button, int buttonState, int key, std::string text, const Point2D& displPosition); const Point2D& GetDisplayPosition() const { return m_DisplayPosition; } void SetDisplayPosition(const Point2D& displPosition) { m_DisplayPosition = displPosition; } const Point3D& GetWorldPosition() const; int GetKey() const { return m_Key; } const char* GetText() const { return m_Text.c_str(); } int GetType() const { return m_Type; } protected: Point2D m_DisplayPosition; int m_Key; std::string m_Text; mutable Point3D m_WorldPosition; mutable bool m_WorldPositionIsSet; }; } // namespace mitk #endif /* DISPLAYPOSITIONozsiEVENT_H_HEADER_INCLUDED_C184F366 */ diff --git a/Core/Code/Interactions/mitkMouseMovePointSetInteractor.h b/Core/Code/Interactions/mitkMouseMovePointSetInteractor.h index ba09431508..51000c8b6e 100644 --- a/Core/Code/Interactions/mitkMouseMovePointSetInteractor.h +++ b/Core/Code/Interactions/mitkMouseMovePointSetInteractor.h @@ -1,69 +1,69 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKMOUSEMOVEPOINTSETINTERACTOR_H_HEADER_INCLUDED_C11202FF #define MITKMOUSEMOVEPOINTSETINTERACTOR_H_HEADER_INCLUDED_C11202FF #include -#include "mitkVector.h" +#include "mitkTypes.h" #include namespace mitk { class DataNode; /** * \brief Interaction with a single point by mouse movement. * * A new point is added by mouse movement, an existing point will be removed before adding a new one. * \ingroup Interaction */ class MITK_CORE_EXPORT MouseMovePointSetInteractor : public PointSetInteractor { public: mitkClassMacro(MouseMovePointSetInteractor, Interactor); mitkNewMacro3Param(Self, const char*, DataNode*, int); mitkNewMacro2Param(Self, const char*, DataNode*); /** * \brief calculates how good the data, this statemachine handles, is hit * by the event. * * overwritten, cause we don't look at the boundingbox, we look at each point * and want to accept mouse movement for setting points */ virtual float CanHandleEvent(StateEvent const* stateEvent) const; protected: /** * \brief Constructor with Param n for limited Set of Points * * if no n is set, then the number of points is unlimited* */ MouseMovePointSetInteractor(const char * type, DataNode* dataNode, int n = -1); /** * \brief Default Destructor **/ virtual ~MouseMovePointSetInteractor(); private: }; } #endif /* MITKMOUSEMOVEPOINTSETINTERACTOR_H_HEADER_INCLUDED_C11202FF */ diff --git a/Core/Code/Interactions/mitkNodeDepententPointSetInteractor.h b/Core/Code/Interactions/mitkNodeDepententPointSetInteractor.h index 8c2d6a933f..11864a9102 100644 --- a/Core/Code/Interactions/mitkNodeDepententPointSetInteractor.h +++ b/Core/Code/Interactions/mitkNodeDepententPointSetInteractor.h @@ -1,77 +1,77 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKNodeDepententPointSetInteractor_H_HEADER_INCLUDED #define MITKNodeDepententPointSetInteractor_H_HEADER_INCLUDED #include -#include "mitkVector.h" +#include "mitkTypes.h" #include #include #include namespace mitk { /** * \brief PointSetInteraction that is dependent on the visibility property of a data node. * * The interactor checks if the renderwindow specific property "visible" of a different node (e.g. image) * specified by @param dependentDataNode is true. The specific renderwindow is specified by the sender of the event. * If the property is true the the object behaves as described by PointSetInteractor. * If not, interaction is blocked. * * This class shows how to write an interactor, that is dependent on a special property of the associated node. * See bug #6047 for further information and a patch to test this class embedded in tutorial Step 5. * \ingroup Interaction */ class MITK_CORE_EXPORT NodeDepententPointSetInteractor : public PointSetInteractor { public: mitkClassMacro(NodeDepententPointSetInteractor, PointSetInteractor); mitkNewMacro4Param(Self, const char*, DataNode*, DataNode*, int); mitkNewMacro3Param(Self, const char*, DataNode*, DataNode*); /** * \brief Checks visibility of the specified node (e.g. image), * returns 0 if node is not visible in sending render window * If Sender within stateEvent is NULL a value of 0 is returned. */ virtual float CanHandleEvent(StateEvent const* stateEvent) const; protected: /** * \brief Constructor with Param n for limited Set of Points * * If no n is set, then the number of points is unlimited * n=0 is not supported. In this case, n is set to 1. */ NodeDepententPointSetInteractor(const char * type, DataNode* dataNode, DataNode* dependentDataNode, int n = -1); /** * \brief Default Destructor **/ virtual ~NodeDepententPointSetInteractor(); public: mitk::DataNode::Pointer m_DependentDataNode; }; } #endif /* MITKNodeDepententPointSetInteractor_H_HEADER_INCLUDED */ diff --git a/Core/Code/Interactions/mitkPointSetInteractor.h b/Core/Code/Interactions/mitkPointSetInteractor.h index 45b3209a98..8677200787 100644 --- a/Core/Code/Interactions/mitkPointSetInteractor.h +++ b/Core/Code/Interactions/mitkPointSetInteractor.h @@ -1,128 +1,128 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKPOINTSETINTERACTOR_H_HEADER_INCLUDED_C11202FF #define MITKPOINTSETINTERACTOR_H_HEADER_INCLUDED_C11202FF #include -#include "mitkVector.h" +#include "mitkTypes.h" #include namespace mitk { class DataNode; /** * \brief Interaction with a set of points. * * Points can be added, removed and moved. * In case the interaction shall be done on a * loaded set of points, the associated data * object (mitkPointSet) needs to be loaded * prior to the instanciation of this object. * The number of points are checked and the internal * statemachine set to the apropriate state. * The management of 0 points is not supported. * In this case, the amount of managed points is set to 1. * \ingroup Interaction */ class MITK_CORE_EXPORT PointSetInteractor : public Interactor { public: mitkClassMacro(PointSetInteractor, Interactor); mitkNewMacro3Param(Self, const char*, DataNode*, int); mitkNewMacro2Param(Self, const char*, DataNode*); /** * @brief Clears all the elements from the given timeStep in the list with undo-functionality and * resets the statemachine */ void Clear( unsigned int timeStep = 0, ScalarType timeInMS = 0.0 ); itkGetMacro( Precision, unsigned int ); itkSetMacro( Precision, unsigned int ); /** * \brief calculates how good the data, this statemachine handles, is hit * by the event. * * overwritten, cause we don't look at the boundingbox, we look at each point */ virtual float CanHandleEvent(StateEvent const* stateEvent) const; /** *@brief If data changed then initialize according to numbers of loaded points **/ virtual void DataChanged(); protected: /** * \brief Constructor with Param n for limited Set of Points * * If no n is set, then the number of points is unlimited * n=0 is not supported. In this case, n is set to 1. */ PointSetInteractor(const char * type, DataNode* dataNode, int n = -1); /** * \brief Default Destructor **/ virtual ~PointSetInteractor(); /** * @brief Convert the given Actions to Operations and send to data and UndoController */ virtual bool ExecuteAction( Action* action, mitk::StateEvent const* stateEvent ); /** \brief Deselects the Points in the PointSet. * supports Undo if enabled */ void UnselectAll( unsigned int timeStep = 0, ScalarType timeInMS = 0.0 ); /** * \brief Selects the point. * supports Undo if enabled. * \param position Needed for declaring operations */ void SelectPoint( int position, unsigned int timeStep = 0, ScalarType timeInMS = 0.0 ); /** \brief to calculate a direction vector from last point and actual * point */ Point3D m_LastPoint; /** \brief summ-vector for Movement */ Vector3D m_SumVec; /** \brief to store the value of precision to pick a point */ unsigned int m_Precision; private: /** * \brief the number of possible points in this object * * if -1, then no limit set */ int m_N; /** * @brief Init the StatateMachine according to the current number of points in case of a loaded pointset. **/ void InitAccordingToNumberOfPoints(); }; } #endif /* MITKPOINTSETINTERACTOR_H_HEADER_INCLUDED_C11202FF */ diff --git a/Core/Code/Interactions/mitkPositionEvent.cpp b/Core/Code/Interactions/mitkPositionEvent.cpp index f4eab0dde6..8c4d4bd1d5 100644 --- a/Core/Code/Interactions/mitkPositionEvent.cpp +++ b/Core/Code/Interactions/mitkPositionEvent.cpp @@ -1,26 +1,26 @@ /*=================================================================== 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 "mitkPositionEvent.h" -#include "mitkVector.h" +#include "mitkTypes.h" mitk::PositionEvent::PositionEvent(mitk::BaseRenderer* sender, int type, int button, int buttonState, int key, const mitk::Point2D& displPosition, const mitk::Point3D& worldPosition) : DisplayPositionEvent(sender, type, button, buttonState, key, displPosition) { m_WorldPosition = worldPosition; m_WorldPositionIsSet = true; } diff --git a/Core/Code/Interactions/mitkPositionEvent.h b/Core/Code/Interactions/mitkPositionEvent.h index 689d1d9c94..2388565ed5 100644 --- a/Core/Code/Interactions/mitkPositionEvent.h +++ b/Core/Code/Interactions/mitkPositionEvent.h @@ -1,55 +1,55 @@ /*=================================================================== 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. ===================================================================*/ #ifndef POSITIONEVENT_H_HEADER_INCLUDED_C184F366 #define POSITIONEVENT_H_HEADER_INCLUDED_C184F366 #include #include "mitkDisplayPositionEvent.h" -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { //##Documentation //## @brief Event that stores coordinates //## //## Stores display position of the mouse and 3D world position in mm. //## @ingroup Interaction /** * \deprecatedSince{2013_03} mitk::PositionEvent is deprecated. Use mitk::InteractionPositionEvent instead. * Refer to \see DataInteractionPage for general information about the concept of the new implementation. */ class MITK_CORE_EXPORT PositionEvent : public DisplayPositionEvent { public: //##Documentation //## @brief Constructor with all necessary arguments. //## //## @param sender: the widget, that caused that event, so that it can be asked for worldCoordinates. changed later to a focus //## @param type, button, buttonState, key: information from the Event //## @param displPosition: the 2D Position e.g. from the mouse //## @param worldPosition: the 3D position e.g. from a picking PositionEvent(BaseRenderer* sender, int type, int button, int buttonState, int key, const Point2D& displPosition, const Point3D& worldPosition); }; } // namespace mitk #endif /* POSITIONEVENT_H_HEADER_INCLUDED_C184F366 */ diff --git a/Core/Code/Interactions/mitkPositionTracker.cpp b/Core/Code/Interactions/mitkPositionTracker.cpp index e5e46d41f2..ba429a6dcd 100755 --- a/Core/Code/Interactions/mitkPositionTracker.cpp +++ b/Core/Code/Interactions/mitkPositionTracker.cpp @@ -1,84 +1,84 @@ /*=================================================================== 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 #include #include #include #include #include #include #include #include #include #include -#include // for PointDataType +#include // for PointDataType #include mitk::PositionTracker::PositionTracker(const char * type, mitk::OperationActor* /*operationActor*/) : mitk::StateMachine(type) {} bool mitk::PositionTracker::ExecuteAction(Action* /*action*/, mitk::StateEvent const* stateEvent) { bool ok = false; const DisplayPositionEvent* displayPositionEvent = dynamic_cast(stateEvent->GetEvent()); mitk::DataNode::Pointer dtnode; mitk::DataStorage* ds = NULL; if (displayPositionEvent == NULL) return false; if (stateEvent->GetEvent()->GetSender()!=NULL) { ds = stateEvent->GetEvent()->GetSender()->GetDataStorage(); } else { itkWarningMacro(<<"StateEvent::GetSender()==NULL - setting timeInMS to 0"); return false; } if (ds == NULL) return false; // looking for desired point set dtnode = ds->GetNode(mitk::NodePredicateProperty::New("inputdevice", mitk::BoolProperty::New(true))); if (dtnode.IsNull()) return false; dtnode->SetIntProperty("BaseRendererMapperID", stateEvent->GetEvent()->GetSender()->GetMapperID()); mitk::PointSet* ps = dynamic_cast(dtnode->GetData()); if (ps == NULL) return false; int position = 0; if( ps->GetPointSet()->GetPoints()->IndexExists( position )) //first element { ps->GetPointSet()->GetPoints()->SetElement( position, displayPositionEvent->GetWorldPosition()); } else { mitk::PointSet::PointDataType pointData = {static_cast(position) , false /*selected*/, mitk::PTUNDEFINED}; ps->GetPointSet()->GetPointData()->InsertElement(position, pointData); ps->GetPointSet()->GetPoints()->InsertElement(position, displayPositionEvent->GetWorldPosition()); } ps->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return ok; } diff --git a/Core/Code/Interactions/mitkWheelEvent.cpp b/Core/Code/Interactions/mitkWheelEvent.cpp index 3b52a99640..4ee383dc5a 100644 --- a/Core/Code/Interactions/mitkWheelEvent.cpp +++ b/Core/Code/Interactions/mitkWheelEvent.cpp @@ -1,31 +1,31 @@ /*=================================================================== 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 "mitkWheelEvent.h" -#include "mitkVector.h" +#include "mitkTypes.h" mitk::WheelEvent::WheelEvent(mitk::BaseRenderer* sender, int type, int button, int buttonState, int key, const mitk::Point2D& displPosition, int delta) : DisplayPositionEvent(sender, type, button, buttonState, key, displPosition) { //m_WorldPosition = worldPosition; //m_WorldPositionIsSet = true; m_Delta = delta; } int mitk::WheelEvent::GetDelta() const { return m_Delta; } diff --git a/Core/Code/Interactions/mitkWheelEvent.h b/Core/Code/Interactions/mitkWheelEvent.h index 4425703d26..11c3ba54ae 100644 --- a/Core/Code/Interactions/mitkWheelEvent.h +++ b/Core/Code/Interactions/mitkWheelEvent.h @@ -1,60 +1,60 @@ /*=================================================================== 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. ===================================================================*/ #ifndef WheelEvent_H_HEADER_INCLUDED_C184F366 #define WheelEvent_H_HEADER_INCLUDED_C184F366 #include #include "mitkDisplayPositionEvent.h" -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { //##Documentation //## @brief Event that stores coordinates and rotation on mouse wheel events //## //## Stores display position of the mouse and 3D world position in mm. //## @ingroup Interaction /** * \deprecatedSince{2013_03} mitk::WheelEvent is deprecated. Use mitk::MouseWheelEvent instead. * Refer to \see DataInteractionPage for general information about the concept of the new implementation. */ class MITK_CORE_EXPORT WheelEvent : public DisplayPositionEvent { public: //##Documentation //## @brief Constructor with all necessary arguments. //## //## @param sender: the widget, that caused that event, so that it can be asked for worldCoordinates. changed later to a focus //## @param type, button, buttonState, key: information from the Event //## @param displPosition: the 2D Position e.g. from the mouse //## @param worldPosition: the 3D position e.g. from a picking //## @param delta: the movement of the mousewheel WheelEvent(BaseRenderer* sender, int type, int button, int buttonState, int key, const Point2D& displPosition, int delta); int GetDelta() const; protected: int m_Delta; }; } // namespace mitk #endif /* WheelEvent_H_HEADER_INCLUDED_C184F366 */ diff --git a/Core/Code/Testing/mitkAffineTransformBaseTest.cpp b/Core/Code/Testing/mitkAffineTransformBaseTest.cpp index 9f257dd1bf..f7e70df745 100644 --- a/Core/Code/Testing/mitkAffineTransformBaseTest.cpp +++ b/Core/Code/Testing/mitkAffineTransformBaseTest.cpp @@ -1,185 +1,185 @@ /*=================================================================== 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 "mitkVector.h" +#include "mitkTypes.h" #include "itkScalableAffineTransform.h" #include "mitkMatrixConvert.h" #include "mitkTestingMacros.h" using namespace mitk; static Vector3D offset; static Matrix3D rotation; static Point3D originalPoint; static double originalPointDouble[4]; static vtkMatrix4x4* homogenMatrix; static vtkMatrix4x4* expectedHomogenousMatrix; static const double expectedPointAfterTransformation[] = {2, 4, 4, 1}; static void Setup() { originalPoint[0] = 1.0; originalPoint[1] = 0.0; originalPoint[2] = 0.0; for (int i = 0; i < 3; i++) originalPointDouble[i] = originalPoint[i]; // same point as the Point3D version originalPointDouble[3] = 1; // homogenous extension offset[0] = 2.0; offset[1] = 3.0; offset[2] = 4.0; - // 90° rotation + // 90� rotation rotation.Fill(0); rotation[0][1] = -1; rotation[1][0] = 1; // prepare a Matrix which shall be set later to a specific // homogen matrix by TransferItkTransformToVtkMatrix // this makes sure, that the initialization to the identity does not // overshadow any bugs in TransferItkTransformToVtkMatrix // (it actually did that by "helping out" TransferItkTransformToVtkMatrix // by setting the (3,3) element to 1). homogenMatrix = vtkMatrix4x4::New(); for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) homogenMatrix->SetElement(i,j, i+j*j); // just some not trivial value // set the expected homogenous matrix result expectedHomogenousMatrix = vtkMatrix4x4::New(); expectedHomogenousMatrix->Zero(); expectedHomogenousMatrix->SetElement(0,1,-1); expectedHomogenousMatrix->SetElement(1,0,1); expectedHomogenousMatrix->SetElement(0,3,2); expectedHomogenousMatrix->SetElement(1,3,3); expectedHomogenousMatrix->SetElement(2,3,4); expectedHomogenousMatrix->SetElement(3,3,1); } /** * This first test basically assures that we understand the usage of AffineTransform3D correct. * Meaning that the rotation is set by SetMatrix and the translation is set by SetOffset */ static void testIfPointIsTransformedAsExpected(void) { Setup(); /** construct the transformation */ AffineTransform3D::Pointer transform = AffineTransform3D::New(); transform->SetOffset(offset); transform->SetMatrix(rotation); TransferItkTransformToVtkMatrix(transform.GetPointer(), homogenMatrix); /** Let a point be transformed by the AffineTransform3D */ Point3D pointTransformedByAffineTransform3D = transform->TransformPoint(originalPoint); /** assert that the transformation was successful */ bool pointCorrect = true; for (int i = 0; i < 3; i++) // only first three since no homogenous coordinates pointCorrect &= Equal(pointTransformedByAffineTransform3D[i], expectedPointAfterTransformation[i]); MITK_TEST_CONDITION(pointCorrect, "Point has been correctly transformed by AffineTranform3D") } /** * This test ensures that the function TransferItkTransformToVtkMatrix translates the AffineTransform3D * correctly to a VtkMatrix4x4 */ static void testTransferItkTransformToVtkMatrix(void) { Setup(); AffineTransform3D::Pointer transform = AffineTransform3D::New(); transform->SetOffset(offset); transform->SetMatrix(rotation); TransferItkTransformToVtkMatrix(transform.GetPointer(), homogenMatrix); bool allElementsEqual = true; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) allElementsEqual &= Equal(homogenMatrix->GetElement(i,j), expectedHomogenousMatrix->GetElement(i,j)); MITK_TEST_CONDITION(allElementsEqual, "Homogenous Matrix is set as expected") } /** * This test basically is just a sanity check and should be PASSED exactly when both * testTransferItkTransformToVtkMatrix and testIfPointIsTransformedAsExpected are PASSED. * Tests if we get the same * result by using the AffineTransform3D to transform a point or the vtkMatrix4x4 which we got by applying * the TransferItkTransformToVtkMatrix function. This test e.g. ensures we made no mistake in our * reference results. * */ static void testIfBothTransformationsProduceSameResults(void) { Setup(); /** * create both a AffineTransform3D * and let this AffineTransform describe also a homogenous 4x4 Matrix vtkMatrix * by using our transfer method */ AffineTransform3D::Pointer transform = AffineTransform3D::New(); transform->SetOffset(offset); transform->SetMatrix(rotation); TransferItkTransformToVtkMatrix(transform.GetPointer(), homogenMatrix); /** Let a point be transformed by the AffineTransform3D and by homogenMatrix */ Point3D pointTransformedByAffineTransform3D = transform->TransformPoint(originalPoint); double* pointTransformedByHomogenous= homogenMatrix->MultiplyDoublePoint(originalPointDouble); /* check if results match */ bool pointsMatch = true; for (int i = 0; i < 3; i++) // only first three since no homogenous coordinates pointsMatch &= Equal(pointTransformedByAffineTransform3D[i], pointTransformedByHomogenous[i]); bool homogenousComponentCorrect = Equal(1, pointTransformedByHomogenous[3]); MITK_TEST_CONDITION(pointsMatch && homogenousComponentCorrect, "Point transformed by AffineTransform and homogenous coordinates match") } /** * This test shall ensure and document the basic functionality of the * itk AffineTransformation functionality and test some basic transformation functionalities provided by mitk. */ int mitkAffineTransformBaseTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN("AffineTransformationBaseTest"); testIfPointIsTransformedAsExpected(); testTransferItkTransformToVtkMatrix(); testIfBothTransformationsProduceSameResults(); MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkClippedSurfaceBoundsCalculatorTest.cpp b/Core/Code/Testing/mitkClippedSurfaceBoundsCalculatorTest.cpp index 13d97a5ff8..bd3a2a2bb2 100644 --- a/Core/Code/Testing/mitkClippedSurfaceBoundsCalculatorTest.cpp +++ b/Core/Code/Testing/mitkClippedSurfaceBoundsCalculatorTest.cpp @@ -1,484 +1,484 @@ /*=================================================================== 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 "mitkTestingMacros.h" #include #include "mitkClippedSurfaceBoundsCalculator.h" #include "mitkGeometry3D.h" #include "mitkGeometry2D.h" -#include "mitkVector.h" +#include "mitkTypes.h" static void CheckPlanesInsideBoundingBoxOnlyOnOneSlice(mitk::Geometry3D::Pointer geometry3D) { //Check planes which are inside the bounding box mitk::ClippedSurfaceBoundsCalculator* calculator = new mitk::ClippedSurfaceBoundsCalculator(); mitk::Image::Pointer image = mitk::Image::New(); image->Initialize( mitk::MakePixelType(), *(geometry3D.GetPointer()) ); //Check planes which are only on one slice: //Slice 0 mitk::Point3D origin; origin[0] = 511; origin[1] = 0; origin[2] = 0; mitk::Vector3D normal; mitk::FillVector3D(normal, 0, 0, 1); mitk::PlaneGeometry::Pointer planeOnSliceZero = mitk::PlaneGeometry::New(); planeOnSliceZero->InitializePlane(origin, normal); calculator->SetInput( planeOnSliceZero , image); calculator->Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 0, "Check if plane is on slice 0"); //Slice 3 origin[2] = 3; mitk::PlaneGeometry::Pointer planeOnSliceThree = mitk::PlaneGeometry::New(); planeOnSliceThree->InitializePlane(origin, normal); planeOnSliceThree->SetImageGeometry(false); calculator->SetInput( planeOnSliceThree , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 3 && minMax.second == 3, "Check if plane is on slice 3"); //Slice 17 origin[2] = 17; mitk::PlaneGeometry::Pointer planeOnSliceSeventeen = mitk::PlaneGeometry::New(); planeOnSliceSeventeen->InitializePlane(origin, normal); calculator->SetInput( planeOnSliceSeventeen , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 17 && minMax.second == 17, "Check if plane is on slice 17"); //Slice 20 origin[2] = 19; mitk::PlaneGeometry::Pointer planeOnSliceTwenty = mitk::PlaneGeometry::New(); planeOnSliceTwenty->InitializePlane(origin, normal); calculator->SetInput( planeOnSliceTwenty , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 19 && minMax.second == 19, "Check if plane is on slice 19"); delete calculator; } static void CheckPlanesInsideBoundingBox(mitk::Geometry3D::Pointer geometry3D) { //Check planes which are inside the bounding box mitk::ClippedSurfaceBoundsCalculator* calculator = new mitk::ClippedSurfaceBoundsCalculator(); mitk::Image::Pointer image = mitk::Image::New(); image->Initialize( mitk::MakePixelType(), *(geometry3D.GetPointer()) ); //Check planes which are only on one slice: //Slice 0 mitk::Point3D origin; origin[0] = 511; // Set to 511.9 so that the intersection point is inside the bounding box origin[1] = 0; origin[2] = 0; mitk::Vector3D normal; mitk::FillVector3D(normal, 1, 0, 0); mitk::PlaneGeometry::Pointer planeSagittalOne = mitk::PlaneGeometry::New(); planeSagittalOne->InitializePlane(origin, normal); calculator->SetInput( planeSagittalOne , image); calculator->Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 19, "Check if plane is from slice 0 to slice 19"); //Slice 3 origin[0] = 256; MITK_INFO << "Case1 origin: " << origin; mitk::PlaneGeometry::Pointer planeSagittalTwo = mitk::PlaneGeometry::New(); planeSagittalTwo->InitializePlane(origin, normal); MITK_INFO << "PlaneNormal: " << planeSagittalTwo->GetNormal(); MITK_INFO << "PlaneOrigin: " << planeSagittalTwo->GetOrigin(); calculator->SetInput( planeSagittalTwo , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 19, "Check if plane is from slice 0 to slice 19"); //Slice 17 origin[0] = 0; // Set to 0.1 so that the intersection point is inside the bounding box mitk::PlaneGeometry::Pointer planeOnSliceSeventeen = mitk::PlaneGeometry::New(); planeOnSliceSeventeen->InitializePlane(origin, normal); calculator->SetInput( planeOnSliceSeventeen , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 19, "Check if plane is from slice 0 to slice 19"); //Crooked planes: origin[0] = 0; origin[1] = 507; origin[2] = 0; normal[0] = 1; normal[1] = -1; normal[2] = 1; mitk::PlaneGeometry::Pointer planeCrookedOne = mitk::PlaneGeometry::New(); planeCrookedOne->InitializePlane(origin, normal); calculator->SetInput( planeCrookedOne , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 4, "Check if plane is from slice 0 to slice 4 with inclined plane"); origin[0] = 512; origin[1] = 0; origin[2] = 16; mitk::PlaneGeometry::Pointer planeCrookedTwo = mitk::PlaneGeometry::New(); planeCrookedTwo->InitializePlane(origin, normal); calculator->SetInput( planeCrookedTwo , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; MITK_TEST_CONDITION(minMax.first == 17 && minMax.second == 19, "Check if plane is from slice 17 to slice 19 with inclined plane"); origin[0] = 511; origin[1] = 0; origin[2] = 0; normal[1] = 0; normal[2] = 0.04; mitk::PlaneGeometry::Pointer planeCrookedThree = mitk::PlaneGeometry::New(); planeCrookedThree->InitializePlane(origin, normal); calculator->SetInput( planeCrookedThree , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 19, "Check if plane is from slice 0 to slice 19 with inclined plane"); delete calculator; } static void CheckPlanesOutsideOfBoundingBox(mitk::Geometry3D::Pointer geometry3D) { //Check planes which are outside of the bounding box mitk::ClippedSurfaceBoundsCalculator* calculator = new mitk::ClippedSurfaceBoundsCalculator(); mitk::Image::Pointer image = mitk::Image::New(); image->Initialize( mitk::MakePixelType(), *(geometry3D.GetPointer()) ); //In front of the bounding box mitk::Point3D origin; origin[0] = 511; origin[1] = 0; origin[2] = -5; mitk::Vector3D normal; mitk::FillVector3D(normal, 0, 0, 1); mitk::PlaneGeometry::Pointer planeInFront = mitk::PlaneGeometry::New(); planeInFront->InitializePlane(origin, normal); calculator->SetInput( planeInFront , image); calculator->Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); //Behind the bounding box origin[2] = 515; mitk::PlaneGeometry::Pointer planeBehind = mitk::PlaneGeometry::New(); planeBehind->InitializePlane(origin, normal); calculator->SetInput( planeBehind , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); //Above origin[1] = 515; mitk::FillVector3D(normal, 0, 1, 0); mitk::PlaneGeometry::Pointer planeAbove = mitk::PlaneGeometry::New(); planeAbove->InitializePlane(origin, normal); calculator->SetInput( planeAbove , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); //Below origin[1] = -5; mitk::PlaneGeometry::Pointer planeBelow = mitk::PlaneGeometry::New(); planeBelow->InitializePlane(origin, normal); calculator->SetInput( planeBelow , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); //Left side origin[0] = -5; mitk::FillVector3D(normal, 1, 0, 0); mitk::PlaneGeometry::Pointer planeLeftSide = mitk::PlaneGeometry::New(); planeLeftSide->InitializePlane(origin, normal); calculator->SetInput( planeLeftSide , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); //Right side origin[1] = 515; mitk::PlaneGeometry::Pointer planeRightSide = mitk::PlaneGeometry::New(); planeRightSide->InitializePlane(origin, normal); calculator->SetInput( planeRightSide , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); delete calculator; } static void CheckIntersectionPointsOfTwoGeometry3D(mitk::Geometry3D::Pointer firstGeometry3D, mitk::Geometry3D::Pointer secondGeometry3D) { mitk::ClippedSurfaceBoundsCalculator* calculator = new mitk::ClippedSurfaceBoundsCalculator(); mitk::Image::Pointer firstImage = mitk::Image::New(); firstImage->Initialize( mitk::MakePixelType(), *(firstGeometry3D.GetPointer()) ); calculator->SetInput( secondGeometry3D, firstImage); calculator->Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMax = calculator->GetMinMaxSpatialDirectionZ(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 19, "Check if plane is from slice 0 to slice 19"); } static void CheckIntersectionWithPointCloud( mitk::Geometry3D::Pointer geometry3D ) { //Check planes which are inside the bounding box mitk::Image::Pointer image = mitk::Image::New(); image->Initialize( mitk::MakePixelType(), *(geometry3D.GetPointer()) ); { mitk::Point3D pnt1, pnt2; pnt1[0] = 3; pnt1[1] = 5; pnt1[2] = 3; pnt2[0] = 8; pnt2[1] = 3; pnt2[2] = 8; mitk::ClippedSurfaceBoundsCalculator::PointListType pointlist; pointlist.push_back( pnt1 ); pointlist.push_back( pnt2 ); mitk::ClippedSurfaceBoundsCalculator calculator; calculator.SetInput( pointlist, image ); calculator.Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMaxZ = calculator.GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMaxZ.first == 3 && minMaxZ.second == 8, "Check if points span from slice 3 to slice 8 in axial"); mitk::ClippedSurfaceBoundsCalculator::OutputType minMaxX = calculator.GetMinMaxSpatialDirectionX(); MITK_TEST_CONDITION(minMaxX.first == 3 && minMaxX.second == 5, "Check if points span from slice 3 to slice 5 in sagittal"); } { mitk::Point3D pnt1, pnt2; pnt1.Fill( -3 ); pnt2.Fill( 600 ); mitk::ClippedSurfaceBoundsCalculator::PointListType pointlist; pointlist.push_back( pnt1 ); pointlist.push_back( pnt2 ); mitk::ClippedSurfaceBoundsCalculator calculator; calculator.SetInput( pointlist, image ); calculator.Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMaxZ = calculator.GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMaxZ.first == 0 && minMaxZ.second == 19, "Check if points are correctly clipped to slice 0 and slice 19 in axial"); mitk::ClippedSurfaceBoundsCalculator::OutputType minMaxX = calculator.GetMinMaxSpatialDirectionX(); MITK_TEST_CONDITION(minMaxX.first == 0 && minMaxX.second == 511, "Check if points are correctly clipped to slice 0 and slice 511 in sagittal"); } } int mitkClippedSurfaceBoundsCalculatorTest(int, char* []) { // always start with this! MITK_TEST_BEGIN("ClippedSurfaceBoundsCalculator"); /** The class mitkClippedSurfaceBoundsCalculator calculates the intersection points of a PlaneGeometry and a Geometry3D. * This unittest checks if the correct min and max values for the three spatial directions (x, y, z) * are calculated. To test this we define artifical PlaneGeometries and Geometry3Ds and test different * scenarios: * * 1. planes which are inside the bounding box of a 3D geometry but only on one slice * 2. planes which are outside of the bounding box * 3. planes which are inside the bounding box but over more than one slice * * Note: Currently rotated geometries are not tested! */ /********************* Define Geometry3D ***********************/ //Define origin: mitk::Point3D origin; origin[0] = 511; origin[1] = 0; origin[2] = 0; //Define normal: mitk::Vector3D normal; mitk::FillVector3D(normal, 0, 0, 1); //Initialize PlaneGeometry: mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New(); planeGeometry->InitializePlane(origin, normal); //Set Bounds: mitk::BoundingBox::BoundsArrayType bounds = planeGeometry->GetBounds(); bounds[0] = 0; bounds[1] = 512; bounds[2] = 0; bounds[3] = 512; bounds[4] = 0; bounds[5] = 1; planeGeometry->SetBounds(bounds); //Initialize SlicedGeometry3D: mitk::SlicedGeometry3D::Pointer slicedGeometry3D = mitk::SlicedGeometry3D::New(); slicedGeometry3D->InitializeEvenlySpaced(dynamic_cast(planeGeometry.GetPointer()), 20); mitk::Geometry3D::Pointer geometry3D = dynamic_cast< mitk::Geometry3D* > ( slicedGeometry3D.GetPointer() ); geometry3D->SetImageGeometry(true); //Define origin for second Geometry3D; mitk::Point3D origin2; origin2[0] = 511; origin2[1] = 60; origin2[2] = 0; //Define normal: mitk::Vector3D normal2; mitk::FillVector3D(normal2, 0, 1, 0); //Initialize PlaneGeometry: mitk::PlaneGeometry::Pointer planeGeometry2 = mitk::PlaneGeometry::New(); planeGeometry2->InitializePlane(origin2, normal2); //Initialize SlicedGeometry3D: mitk::SlicedGeometry3D::Pointer secondSlicedGeometry3D = mitk::SlicedGeometry3D::New(); secondSlicedGeometry3D->InitializeEvenlySpaced(dynamic_cast(planeGeometry2.GetPointer()), 20); mitk::Geometry3D::Pointer secondGeometry3D = dynamic_cast< mitk::Geometry3D* > ( secondSlicedGeometry3D.GetPointer() ); secondGeometry3D->SetImageGeometry(true); /***************************************************************/ CheckPlanesInsideBoundingBoxOnlyOnOneSlice(geometry3D); CheckPlanesOutsideOfBoundingBox(geometry3D); CheckPlanesInsideBoundingBox(geometry3D); CheckIntersectionPointsOfTwoGeometry3D(geometry3D, secondGeometry3D); CheckIntersectionWithPointCloud( geometry3D ); /** ToDo: * test also rotated 3D geometry! */ MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkExtractSliceFilterTest.cpp b/Core/Code/Testing/mitkExtractSliceFilterTest.cpp index 3fed1eb757..5ceddaf98e 100644 --- a/Core/Code/Testing/mitkExtractSliceFilterTest.cpp +++ b/Core/Code/Testing/mitkExtractSliceFilterTest.cpp @@ -1,1162 +1,1162 @@ /*=================================================================== 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 #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 //use this to create the test volume on the fly #define CREATE_VOLUME //use this to save the created volume //#define SAVE_VOLUME //use this to calculate the error from the sphere mathematical model to our pixel based one //#define CALC_TESTFAILURE_DEVIATION //use this to render an oblique slice through a specified image //#define SHOW_SLICE_IN_RENDER_WINDOW //use this to have infos printed in mbilog //#define EXTRACTOR_DEBUG /*these are the deviations calculated by the function CalcTestFailureDeviation (see for details)*/ #define Testfailure_Deviation_Mean_128 0.853842 #define Testfailure_Deviation_Volume_128 0.145184 #define Testfailure_Deviation_Diameter_128 1.5625 #define Testfailure_Deviation_Mean_256 0.397693 #define Testfailure_Deviation_Volume_256 0.0141357 #define Testfailure_Deviation_Diameter_256 0.78125 #define Testfailure_Deviation_Mean_512 0.205277 #define Testfailure_Deviation_Volume_512 0.01993 #define Testfailure_Deviation_Diameter_512 0.390625 class mitkExtractSliceFilterTestClass{ public: static void TestSlice(mitk::PlaneGeometry* planeGeometry, std::string testname) { TestPlane = planeGeometry; TestName = testname; mitk::ScalarType centerCoordValue = TestvolumeSize / 2.0; mitk::ScalarType center[3] = {centerCoordValue, centerCoordValue, centerCoordValue}; mitk::Point3D centerIndex(center); double radius = TestvolumeSize / 4.0; if(TestPlane->Distance(centerIndex) >= radius ) return;//outside sphere //feed ExtractSliceFilter mitk::ExtractSliceFilter::Pointer slicer = mitk::ExtractSliceFilter::New(); slicer->SetInput(TestVolume); slicer->SetWorldGeometry(TestPlane); slicer->Update(); MITK_TEST_CONDITION_REQUIRED(slicer->GetOutput() != NULL, "Extractor returned a slice"); mitk::Image::Pointer reslicedImage = slicer->GetOutput(); AccessFixedDimensionByItk(reslicedImage, TestSphereRadiusByItk, 2); AccessFixedDimensionByItk(reslicedImage, TestSphereAreaByItk, 2); /* double devArea, devDiameter; if(TestvolumeSize == 128.0){ devArea = Testfailure_Deviation_Volume_128; devDiameter = Testfailure_Deviation_Diameter_128; } else if(TestvolumeSize == 256.0){devArea = Testfailure_Deviation_Volume_256; devDiameter = Testfailure_Deviation_Diameter_256;} else if (TestvolumeSize == 512.0){devArea = Testfailure_Deviation_Volume_512; devDiameter = Testfailure_Deviation_Diameter_512;} else{devArea = Testfailure_Deviation_Volume_128; devDiameter = Testfailure_Deviation_Diameter_128;} */ std::string areatestName = TestName.append(" area"); std::string diametertestName = TestName.append(" testing diameter"); //TODO think about the deviation, 1% makes no sense at all MITK_TEST_CONDITION(std::abs(100 - testResults.percentageAreaCalcToPixel) < 1, areatestName ); MITK_TEST_CONDITION(std::abs(100 - testResults.percentageRadiusToPixel) < 1, diametertestName ); #ifdef EXTRACTOR_DEBUG MITK_INFO << TestName << " >>> " << "planeDistanceToSphereCenter: " << testResults.planeDistanceToSphereCenter; MITK_INFO << "area in pixels: " << testResults.areaInPixel << " <-> area in mm: " << testResults.areaCalculated << " = " << testResults.percentageAreaCalcToPixel << "%"; MITK_INFO << "calculated diameter: " << testResults.diameterCalculated << " <-> diameter in mm: " << testResults.diameterInMM << " <-> diameter in pixel: " << testResults.diameterInPixel << " = " << testResults.percentageRadiusToPixel << "%"; #endif } /* * get the radius of the slice of a sphere based on pixel distance from edge to edge of the circle. */ template static void TestSphereRadiusByItk (itk::Image* inputImage) { typedef itk::Image InputImageType; //set the index to the middle of the image's edge at x and y axis typename InputImageType::IndexType currentIndexX; currentIndexX[0] = (int)(TestvolumeSize / 2.0); currentIndexX[1] = 0; typename InputImageType::IndexType currentIndexY; currentIndexY[0] = 0; currentIndexY[1] = (int)(TestvolumeSize / 2.0); //remember the last pixel value double lastValueX = inputImage->GetPixel(currentIndexX); double lastValueY = inputImage->GetPixel(currentIndexY); //storage for the index marks std::vector indicesX; std::vector indicesY; /*Get four indices on the edge of the circle*/ while(currentIndexX[1] < TestvolumeSize && currentIndexX[0] < TestvolumeSize) { //move x direction currentIndexX[1] += 1; //move y direction currentIndexY[0] += 1; if(inputImage->GetPixel(currentIndexX) > lastValueX) { //mark the current index typename InputImageType::IndexType markIndex; markIndex[0] = currentIndexX[0]; markIndex[1] = currentIndexX[1]; indicesX.push_back(markIndex); } else if( inputImage->GetPixel(currentIndexX) < lastValueX) { //mark the current index typename InputImageType::IndexType markIndex; markIndex[0] = currentIndexX[0]; markIndex[1] = currentIndexX[1] - 1;//value inside the sphere indicesX.push_back(markIndex); } if(inputImage->GetPixel(currentIndexY) > lastValueY) { //mark the current index typename InputImageType::IndexType markIndex; markIndex[0] = currentIndexY[0]; markIndex[1] = currentIndexY[1]; indicesY.push_back(markIndex); } else if( inputImage->GetPixel(currentIndexY) < lastValueY) { //mark the current index typename InputImageType::IndexType markIndex; markIndex[0] = currentIndexY[0]; markIndex[1] = currentIndexY[1] - 1;//value inside the sphere indicesY.push_back(markIndex); } //found both marks? if(indicesX.size() == 2 && indicesY.size() == 2) break; //the new 'last' values lastValueX = inputImage->GetPixel(currentIndexX); lastValueY = inputImage->GetPixel(currentIndexY); } /* *If we are here we found the four marks on the edge of the circle. *For the case our plane is rotated and shifted, we have to calculate the center of the circle, *else the center is the intersection of both straight lines between the marks. *When we have the center, the diameter of the circle will be checked to the reference value(math!). */ //each distance from the first mark of each direction to the center of the straight line between the marks double distanceToCenterX = std::abs(indicesX[0][1] - indicesX[1][1]) / 2.0; //double distanceToCenterY = std::abs(indicesY[0][0] - indicesY[1][0]) / 2.0; //the center of the straight lines typename InputImageType::IndexType centerX; //typename InputImageType::IndexType centerY; centerX[0] = indicesX[0][0]; centerX[1] = indicesX[0][1] + distanceToCenterX; //TODO think about implicit cast to int. this is not the real center of the image, which could be between two pixels //centerY[0] = indicesY[0][0] + distanceToCenterY; //centerY[1] = inidcesY[0][1]; typename InputImageType::IndexType currentIndex(centerX); lastValueX = inputImage->GetPixel(currentIndex); long sumpixels = 0; std::vector diameterIndices; //move up while(currentIndex[1] < TestvolumeSize) { currentIndex[1] += 1; if( inputImage->GetPixel(currentIndex) != lastValueX) { typename InputImageType::IndexType markIndex; markIndex[0] = currentIndex[0]; markIndex[1] = currentIndex[1] - 1; diameterIndices.push_back(markIndex); break; } sumpixels++; lastValueX = inputImage->GetPixel(currentIndex); } currentIndex[1] -= sumpixels; //move back to center to go in the other direction lastValueX = inputImage->GetPixel(currentIndex); //move down while(currentIndex[1] >= 0) { currentIndex[1] -= 1; if( inputImage->GetPixel(currentIndex) != lastValueX) { typename InputImageType::IndexType markIndex; markIndex[0] = currentIndex[0]; markIndex[1] = currentIndex[1];//outside sphere because we want to calculate the distance from edge to edge diameterIndices.push_back(markIndex); break; } sumpixels++; lastValueX = inputImage->GetPixel(currentIndex); } /* *Now sumpixels should be the apromximate diameter of the circle. This is checked with the calculated diameter from the plane transformation(math). */ mitk::Point3D volumeCenter; volumeCenter[0] = volumeCenter[1] = volumeCenter[2] = TestvolumeSize / 2.0; double planeDistanceToSphereCenter = TestPlane->Distance(volumeCenter); double sphereRadius = TestvolumeSize/4.0; //calculate the radius of the circle cut from the sphere by the plane double diameter = 2.0 * std::sqrt(std::pow(sphereRadius, 2) - std::pow( planeDistanceToSphereCenter , 2)); double percentageRadiusToPixel = 100 / diameter * sumpixels; /* *calculate the radius in mm by the both marks of the center line by using the world coordinates */ //get the points as 3D coordinates mitk::Vector3D diameterPointRight, diameterPointLeft; diameterPointRight[2] = diameterPointLeft[2] = 0.0; diameterPointLeft[0] = diameterIndices[0][0]; diameterPointLeft[1] = diameterIndices[0][1]; diameterPointRight[0] = diameterIndices[1][0]; diameterPointRight[1] = diameterIndices[1][1]; //transform to worldcoordinates TestVolume->GetGeometry()->IndexToWorld(diameterPointLeft, diameterPointLeft); TestVolume->GetGeometry()->IndexToWorld(diameterPointRight, diameterPointRight); //euklidian distance double diameterInMM = ( (diameterPointLeft * -1.0) + diameterPointRight).GetNorm(); testResults.diameterInMM = diameterInMM; testResults.diameterCalculated = diameter; testResults.diameterInPixel = sumpixels; testResults.percentageRadiusToPixel = percentageRadiusToPixel; testResults.planeDistanceToSphereCenter = planeDistanceToSphereCenter; } /*brute force the area pixel by pixel*/ template static void TestSphereAreaByItk (itk::Image* inputImage) { typedef itk::Image InputImageType; typedef itk::ImageRegionConstIterator< InputImageType > ImageIterator; ImageIterator imageIterator( inputImage, inputImage->GetLargestPossibleRegion() ); imageIterator.GoToBegin(); int sumPixelsInArea = 0; while( !imageIterator.IsAtEnd() ) { if(inputImage->GetPixel(imageIterator.GetIndex()) == pixelValueSet) sumPixelsInArea++; ++imageIterator; } mitk::Point3D volumeCenter; volumeCenter[0] = volumeCenter[1] = volumeCenter[2] = TestvolumeSize / 2.0; double planeDistanceToSphereCenter = TestPlane->Distance(volumeCenter); double sphereRadius = TestvolumeSize/4.0; //calculate the radius of the circle cut from the sphere by the plane double radius = std::sqrt(std::pow(sphereRadius, 2) - std::pow( planeDistanceToSphereCenter , 2)); double areaInMM = 3.14159265358979 * std::pow(radius, 2); testResults.areaCalculated = areaInMM; testResults.areaInPixel = sumPixelsInArea; testResults.percentageAreaCalcToPixel = 100 / areaInMM * sumPixelsInArea; } /* * random a voxel. define plane through this voxel. reslice at the plane. compare the pixel vaues of the voxel * in the volume with the pixel value in the resliced image. * there are some indice shifting problems which causes the test to fail for oblique planes. seems like the chosen * worldcoordinate is not corrresponding to the index in the 2D image. and so the pixel values are not the same as * expected. */ static void PixelvalueBasedTest() { /* setup itk image */ typedef itk::Image ImageType; typedef itk::ImageRegionConstIterator< ImageType > ImageIterator; ImageType::Pointer image = ImageType::New(); ImageType::IndexType start; start[0] = start[1] = start[2] = 0; ImageType::SizeType size; size[0] = size[1] = size[2] = 32; ImageType::RegionType imgRegion; imgRegion.SetSize(size); imgRegion.SetIndex(start); image->SetRegions(imgRegion); image->SetSpacing(1.0); image->Allocate(); ImageIterator imageIterator( image, image->GetLargestPossibleRegion() ); imageIterator.GoToBegin(); unsigned short pixelValue = 0; //fill the image with distinct values while ( !imageIterator.IsAtEnd() ) { image->SetPixel(imageIterator.GetIndex(), pixelValue); ++imageIterator; ++pixelValue; } /* end setup itk image */ mitk::Image::Pointer imageInMitk; CastToMitkImage(image, imageInMitk); /*mitk::ImageWriter::Pointer writer = mitk::ImageWriter::New(); writer->SetInput(imageInMitk); std::string file = "C:\\Users\\schroedt\\Desktop\\cube.nrrd"; writer->SetFileName(file); writer->Update();*/ PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Frontal); PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Sagittal); PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Axial); } static void PixelvalueBasedTestByPlane(mitk::Image* imageInMitk, mitk::PlaneGeometry::PlaneOrientation orientation){ typedef itk::Image ImageType; //set the seed of the rand function srand((unsigned)time(0)); /* setup a random orthogonal plane */ int sliceindex = 17;//rand() % 32; bool isFrontside = true; bool isRotated = false; if( orientation == mitk::PlaneGeometry::Axial) { /*isFrontside = false; isRotated = true;*/ } mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New(); plane->InitializeStandardPlane(imageInMitk->GetGeometry(), orientation, sliceindex, isFrontside, isRotated); mitk::Point3D origin = plane->GetOrigin(); mitk::Vector3D normal; normal = plane->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 plane->SetOrigin(origin); //we dont need this any more, because we are only testing orthogonal planes /*mitk::Vector3D rotationVector; rotationVector[0] = randFloat(); rotationVector[1] = randFloat(); rotationVector[2] = randFloat(); float degree = randFloat() * 180.0; mitk::RotationOperation* op = new mitk::RotationOperation(mitk::OpROTATE, plane->GetCenter(), rotationVector, degree); plane->ExecuteOperation(op); delete op;*/ /* end setup plane */ /* define a point in the 3D volume. * add the two axis vectors of the plane (each multiplied with a * random number) to the origin. now the two random numbers * become our index coordinates in the 2D image, because the * length of the axis vectors is 1. */ mitk::Point3D planeOrigin = plane->GetOrigin(); mitk::Vector3D axis0, axis1; axis0 = plane->GetAxisVector(0); axis1 = plane->GetAxisVector(1); axis0.Normalize(); axis1.Normalize(); unsigned char n1 = 7;// rand() % 32; unsigned char n2 = 13;// rand() % 32; mitk::Point3D testPoint3DInWorld; testPoint3DInWorld = planeOrigin + (axis0 * n1) + (axis1 * n2); //get the index of the point in the 3D volume ImageType::IndexType testPoint3DInIndex; imageInMitk->GetGeometry()->WorldToIndex(testPoint3DInWorld, testPoint3DInIndex); mitk::Index3D testPoint2DInIndex; /* end define a point in the 3D volume.*/ //do reslicing at the plane mitk::ExtractSliceFilter::Pointer slicer = mitk::ExtractSliceFilter::New(); slicer->SetInput(imageInMitk); slicer->SetWorldGeometry(plane); slicer->Update(); mitk::Image::Pointer slice = slicer->GetOutput(); // Get TestPoiont3D as Index in Slice slice->GetGeometry()->WorldToIndex(testPoint3DInWorld,testPoint2DInIndex); mitk::Point3D p, sliceIndexToWorld, imageIndexToWorld; p[0] = testPoint2DInIndex[0]; p[1] = testPoint2DInIndex[1]; p[2] = testPoint2DInIndex[2]; slice->GetGeometry()->IndexToWorld(p, sliceIndexToWorld); p[0] = testPoint3DInIndex[0]; p[1] = testPoint3DInIndex[1]; p[2] = testPoint3DInIndex[2]; imageInMitk->GetGeometry()->IndexToWorld(p, imageIndexToWorld); //compare the pixelvalues of the defined point in the 3D volume with the value of the resliced image unsigned short valueAt3DVolume = imageInMitk->GetPixelValueByIndex(testPoint3DInIndex);//image->GetPixel(testPoint3DInIndex); //unsigned short valueAt3DVolumeByWorld = imageInMitk->GetPixelValueByWorldCoordinate(testPoint3DInWorld); unsigned short valueAtSlice = slice->GetPixelValueByIndex(testPoint2DInIndex); //valueAt3DVolume == valueAtSlice is not always working. because of rounding errors //indices are shifted MITK_TEST_CONDITION(valueAt3DVolume == valueAtSlice, "comparing pixelvalues for orthogonal plane"); vtkSmartPointer imageInVtk = vtkSmartPointer::New(); imageInVtk = imageInMitk->GetVtkImageData(); vtkSmartPointer sliceInVtk = vtkSmartPointer::New(); sliceInVtk = slice->GetVtkImageData(); double PixelvalueByMitkOutput = sliceInVtk->GetScalarComponentAsDouble(n1, n2, 0, 0); //double valueVTKinImage = imageInVtk->GetScalarComponentAsDouble(testPoint3DInIndex[0], testPoint3DInIndex[1], testPoint3DInIndex[2], 0); /* Test that everything is working equally if vtkoutput is used instead of the default output * from mitk ImageToImageFilter */ mitk::ExtractSliceFilter::Pointer slicerWithVtkOutput = mitk::ExtractSliceFilter::New(); slicerWithVtkOutput->SetInput(imageInMitk); slicerWithVtkOutput->SetWorldGeometry(plane); slicerWithVtkOutput->SetVtkOutputRequest(true); slicerWithVtkOutput->Update(); vtkSmartPointer vtkImageByVtkOutput = vtkSmartPointer::New(); vtkImageByVtkOutput = slicerWithVtkOutput->GetVtkOutput(); double PixelvalueByVtkOutput = vtkImageByVtkOutput->GetScalarComponentAsDouble(n1, n2, 0, 0); MITK_TEST_CONDITION(PixelvalueByMitkOutput == PixelvalueByVtkOutput, "testing convertion of image output vtk->mitk by reslicer"); /*================ mbilog outputs ===========================*/ #ifdef EXTRACTOR_DEBUG MITK_INFO << "\n" << "TESTINFO index: " << sliceindex << " orientation: " << orientation << " frontside: " << isFrontside << " rotated: " << isRotated; MITK_INFO << "\n" << "slice index to world: " << sliceIndexToWorld; MITK_INFO << "\n" << "image index to world: " << imageIndexToWorld; MITK_INFO << "\n" << "vtk: slice: " << PixelvalueByMitkOutput << ", image: "<< valueVTKinImage; MITK_INFO << "\n" << "testPoint3D InWorld" << testPoint3DInWorld << " is " << testPoint2DInIndex << " in 2D"; MITK_INFO << "\n" << "randoms: " << ((int)n1) << ", " << ((int)n2); MITK_INFO << "\n" << "point is inside plane: " << plane->IsInside(testPoint3DInWorld) << " and volume: " << imageInMitk->GetGeometry()->IsInside(testPoint3DInWorld); MITK_INFO << "\n" << "volume idx: " << testPoint3DInIndex << " = " << valueAt3DVolume ; MITK_INFO << "\n" << "volume world: " << testPoint3DInWorld << " = " << valueAt3DVolumeByWorld ; MITK_INFO << "\n" << "slice idx: " << testPoint2DInIndex << " = " << valueAtSlice ; mitk::Index3D curr; curr[0] = curr[1] = curr[2] = 0; for( int i = 0; i < 32 ; ++i){ for( int j = 0; j < 32; ++j){ ++curr[1]; if(slice->GetPixelValueByIndex(curr) == valueAt3DVolume){ MITK_INFO << "\n" << valueAt3DVolume << " MATCHED mitk " << curr; } } curr[1] = 0; ++curr[0]; } typedef itk::Image Image2DType; Image2DType::Pointer img = Image2DType::New(); CastToItkImage(slice, img); typedef itk::ImageRegionConstIterator< Image2DType > Iterator2D; Iterator2D iter(img, img->GetLargestPossibleRegion()); iter.GoToBegin(); while( !iter.IsAtEnd() ){ if(img->GetPixel(iter.GetIndex()) == valueAt3DVolume) MITK_INFO << "\n" << valueAt3DVolume << " MATCHED itk " << iter.GetIndex(); ++iter; } #endif //EXTRACTOR_DEBUG } /* random a float value */ static float randFloat(){ return (((float)rand()+1.0) / ((float)RAND_MAX + 1.0)) + (((float)rand()+1.0) / ((float)RAND_MAX + 1.0)) / ((float)RAND_MAX + 1.0);} /* create a sphere with the size of the given testVolumeSize*/ static void InitializeTestVolume() { #ifdef CREATE_VOLUME //do sphere creation ItkVolumeGeneration(); #ifdef SAVE_VOLUME //save in file mitk::ImageWriter::Pointer writer = mitk::ImageWriter::New(); writer->SetInput(TestVolume); std::string file; std::ostringstream filename; filename << "C:\\home\\schroedt\\MITK\\Modules\\ImageExtraction\\Testing\\Data\\sphere_"; filename << TestvolumeSize; filename << ".nrrd"; file = filename.str(); writer->SetFileName(file); writer->Update(); #endif//SAVE_VOLUME #endif #ifndef CREATE_VOLUME //read from file mitk::StandardFileLocations::Pointer locator = mitk::StandardFileLocations::GetInstance(); std::string filename = locator->FindFile("sphere_512.nrrd.mhd", "Modules/ImageExtraction/Testing/Data"); mitk::ItkImageFileReader::Pointer reader = mitk::ItkImageFileReader::New(); reader->SetFileName(filename); reader->Update(); TestVolume = reader->GetOutput(); #endif #ifdef CALC_TESTFAILURE_DEVIATION //get the TestFailureDeviation in % AccessFixedDimensionByItk(TestVolume, CalcTestFailureDeviation, 3); #endif } //the test result of the sphere reslice struct SliceProperties{ double planeDistanceToSphereCenter; double diameterInMM; double diameterInPixel; double diameterCalculated; double percentageRadiusToPixel; double areaCalculated; double areaInPixel; double percentageAreaCalcToPixel; }; static mitk::Image::Pointer TestVolume; static double TestvolumeSize; static mitk::PlaneGeometry::Pointer TestPlane; static std::string TestName; static unsigned char pixelValueSet; static SliceProperties testResults; static double TestFailureDeviation; private: /* * Generate a sphere with a radius of TestvolumeSize / 4.0 */ static void ItkVolumeGeneration () { typedef itk::Image TestVolumeType; typedef itk::ImageRegionConstIterator< TestVolumeType > ImageIterator; TestVolumeType::Pointer sphereImage = TestVolumeType::New(); TestVolumeType::IndexType start; start[0] = start[1] = start[2] = 0; TestVolumeType::SizeType size; size[0] = size[1] = size[2] = TestvolumeSize; TestVolumeType::RegionType imgRegion; imgRegion.SetSize(size); imgRegion.SetIndex(start); sphereImage->SetRegions(imgRegion); sphereImage->SetSpacing(1.0); sphereImage->Allocate(); sphereImage->FillBuffer(0); mitk::Vector3D center; center[0] = center[1] = center[2] = TestvolumeSize / 2.0; double radius = TestvolumeSize / 4.0; double pixelValue = pixelValueSet; double distanceToCenter = 0.0; ImageIterator imageIterator( sphereImage, sphereImage->GetLargestPossibleRegion() ); imageIterator.GoToBegin(); mitk::Vector3D currentVoxelInIndex; while ( !imageIterator.IsAtEnd() ) { currentVoxelInIndex[0] = imageIterator.GetIndex()[0]; currentVoxelInIndex[1] = imageIterator.GetIndex()[1]; currentVoxelInIndex[2] = imageIterator.GetIndex()[2]; distanceToCenter = (center + ( currentVoxelInIndex * -1.0 )).GetNorm(); //if distance to center is smaller then the radius of the sphere if( distanceToCenter < radius) { sphereImage->SetPixel(imageIterator.GetIndex(), pixelValue); } ++imageIterator; } CastToMitkImage(sphereImage, TestVolume); } /* calculate the devation of the voxel object to the mathematical sphere object. * this is use to make a statement about the accuracy of the resliced image, eg. the circle's diameter or area. */ template static void CalcTestFailureDeviation (itk::Image* inputImage) { typedef itk::Image InputImageType; typedef itk::ImageRegionConstIterator< InputImageType > ImageIterator; ImageIterator iterator(inputImage, inputImage->GetLargestPossibleRegion()); iterator.GoToBegin(); int volumeInPixel = 0; while( !iterator.IsAtEnd() ) { if(inputImage->GetPixel(iterator.GetIndex()) == pixelValueSet) volumeInPixel++; ++iterator; } double diameter = TestvolumeSize / 2.0; double volumeCalculated = (1.0 / 6.0) * 3.14159265358979 * std::pow(diameter, 3); double volumeDeviation = std::abs( 100 - (100 / volumeCalculated * volumeInPixel) ); typename InputImageType::IndexType index; index[0] = index[1] = TestvolumeSize / 2.0; index[2] = 0; int sumpixels = 0; while (index[2] < TestvolumeSize ) { if(inputImage->GetPixel(index) == pixelValueSet) sumpixels++; index[2] += 1; } double diameterDeviation = std::abs( 100 - (100 / diameter * sumpixels) ); #ifdef DEBUG MITK_INFO << "volume deviation: " << volumeDeviation << " diameter deviation:" << diameterDeviation; #endif mitkExtractSliceFilterTestClass::TestFailureDeviation = (volumeDeviation + diameterDeviation) / 2.0; } }; /*================ #END class ================*/ /*================#BEGIN Instanciation of members ================*/ mitk::Image::Pointer mitkExtractSliceFilterTestClass::TestVolume = mitk::Image::New(); double mitkExtractSliceFilterTestClass::TestvolumeSize = 256.0; mitk::PlaneGeometry::Pointer mitkExtractSliceFilterTestClass::TestPlane = mitk::PlaneGeometry::New(); std::string mitkExtractSliceFilterTestClass::TestName = ""; unsigned char mitkExtractSliceFilterTestClass::pixelValueSet = 255; mitkExtractSliceFilterTestClass::SliceProperties mitkExtractSliceFilterTestClass::testResults = {-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0}; double mitkExtractSliceFilterTestClass::TestFailureDeviation = 0.0; /*================ #END Instanciation of members ================*/ /*================ #BEGIN test main ================*/ int mitkExtractSliceFilterTest(int argc, char* argv[]) { MITK_TEST_BEGIN("mitkExtractSliceFilterTest") //pixelvalue based testing mitkExtractSliceFilterTestClass::PixelvalueBasedTest(); //initialize sphere test volume mitkExtractSliceFilterTestClass::InitializeTestVolume(); mitk::Vector3D spacing = mitkExtractSliceFilterTestClass::TestVolume->GetGeometry()->GetSpacing(); //the center of the sphere = center of image double sphereCenter = mitkExtractSliceFilterTestClass::TestvolumeSize / 2.0; double planeSize = mitkExtractSliceFilterTestClass::TestvolumeSize; /* axial plane */ mitk::PlaneGeometry::Pointer geometryAxial = mitk::PlaneGeometry::New(); geometryAxial->InitializeStandardPlane(planeSize, planeSize, spacing, mitk::PlaneGeometry::Axial, sphereCenter, false, true); geometryAxial->ChangeImageGeometryConsideringOriginOffset(true); mitk::Point3D origin = geometryAxial->GetOrigin(); mitk::Vector3D normal; normal = geometryAxial->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 //geometryAxial->SetOrigin(origin); mitkExtractSliceFilterTestClass::TestSlice(geometryAxial, "Testing axial plane"); /* end axial plane */ /* sagittal plane */ mitk::PlaneGeometry::Pointer geometrySagital = mitk::PlaneGeometry::New(); geometrySagital->InitializeStandardPlane(planeSize, planeSize, spacing, mitk::PlaneGeometry::Sagittal, sphereCenter, true, false); geometrySagital->ChangeImageGeometryConsideringOriginOffset(true); origin = geometrySagital->GetOrigin(); normal = geometrySagital->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 //geometrySagital->SetOrigin(origin); mitkExtractSliceFilterTestClass::TestSlice(geometrySagital, "Testing sagittal plane"); /* sagittal plane */ /* sagittal shifted plane */ mitk::PlaneGeometry::Pointer geometrySagitalShifted = mitk::PlaneGeometry::New(); geometrySagitalShifted->InitializeStandardPlane(planeSize, planeSize, spacing, mitk::PlaneGeometry::Sagittal, (sphereCenter - 14), true, false); geometrySagitalShifted->ChangeImageGeometryConsideringOriginOffset(true); origin = geometrySagitalShifted->GetOrigin(); normal = geometrySagitalShifted->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 //geometrySagitalShifted->SetOrigin(origin); mitkExtractSliceFilterTestClass::TestSlice(geometrySagitalShifted, "Testing sagittal plane shifted"); /* end sagittal shifted plane */ /* coronal plane */ mitk::PlaneGeometry::Pointer geometryCoronal = mitk::PlaneGeometry::New(); geometryCoronal->InitializeStandardPlane(planeSize, planeSize, spacing, mitk::PlaneGeometry::Frontal, sphereCenter, true, false); geometryCoronal->ChangeImageGeometryConsideringOriginOffset(true); origin = geometryCoronal->GetOrigin(); normal = geometryCoronal->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 //geometryCoronal->SetOrigin(origin); mitkExtractSliceFilterTestClass::TestSlice(geometryCoronal, "Testing coronal plane"); /* end coronal plane */ /* oblique plane */ mitk::PlaneGeometry::Pointer obliquePlane = mitk::PlaneGeometry::New(); obliquePlane->InitializeStandardPlane(planeSize, planeSize, spacing, mitk::PlaneGeometry::Sagittal, sphereCenter, true, false); obliquePlane->ChangeImageGeometryConsideringOriginOffset(true); origin = obliquePlane->GetOrigin(); normal = obliquePlane->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 //obliquePlane->SetOrigin(origin); mitk::Vector3D rotationVector; rotationVector[0] = 0.2; rotationVector[1] = 0.4; rotationVector[2] = 0.62; float degree = 37.0; mitk::RotationOperation* op = new mitk::RotationOperation(mitk::OpROTATE, obliquePlane->GetCenter(), rotationVector, degree); obliquePlane->ExecuteOperation(op); delete op; mitkExtractSliceFilterTestClass::TestSlice(obliquePlane, "Testing oblique plane"); /* end oblique plane */ #ifdef SHOW_SLICE_IN_RENDER_WINDOW /*================ #BEGIN vtk render code ================*/ //set reslicer for renderwindow mitk::ItkImageFileReader::Pointer reader = mitk::ItkImageFileReader::New(); std::string filename = "C:\\home\\Pics\\Pic3D.nrrd"; reader->SetFileName(filename); reader->Update(); mitk::Image::Pointer pic = reader->GetOutput(); vtkSmartPointer slicer = vtkSmartPointer::New(); slicer->SetInput(pic->GetVtkImageData()); mitk::PlaneGeometry::Pointer obliquePl = mitk::PlaneGeometry::New(); obliquePl->InitializeStandardPlane(pic->GetGeometry(), mitk::PlaneGeometry::Sagittal, pic->GetGeometry()->GetCenter()[0], true, false); obliquePl->ChangeImageGeometryConsideringOriginOffset(true); mitk::Point3D origin2 = obliquePl->GetOrigin(); mitk::Vector3D n; n = obliquePl->GetNormal(); n.Normalize(); origin2 += n * 0.5;//pixelspacing is 1, so half the spacing is 0.5 obliquePl->SetOrigin(origin2); mitk::Vector3D rotation; rotation[0] = 0.534307; rotation[1] = 0.000439605; rotation[2] = 0.423017; MITK_INFO << rotation; float rotateDegree = 70; mitk::RotationOperation* operation = new mitk::RotationOperation(mitk::OpROTATE, obliquePl->GetCenter(), rotationVector, degree); obliquePl->ExecuteOperation(operation); delete operation; double origin[3]; origin[0] = obliquePl->GetOrigin()[0]; origin[1] = obliquePl->GetOrigin()[1]; origin[2] = obliquePl->GetOrigin()[2]; slicer->SetResliceAxesOrigin(origin); mitk::Vector3D right, bottom, normal; right = obliquePl->GetAxisVector( 0 ); bottom = obliquePl->GetAxisVector( 1 ); normal = obliquePl->GetNormal(); right.Normalize(); bottom.Normalize(); normal.Normalize(); double cosines[9]; mitk::vnl2vtk(right.GetVnlVector(), cosines);//x mitk::vnl2vtk(bottom.GetVnlVector(), cosines + 3);//y mitk::vnl2vtk(normal.GetVnlVector(), cosines + 6);//n slicer->SetResliceAxesDirectionCosines(cosines); slicer->SetOutputDimensionality(2); slicer->Update(); //set vtk renderwindow vtkSmartPointer vtkPlane = vtkSmartPointer::New(); vtkPlane->SetOrigin(0.0, 0.0, 0.0); //These two points define the axes of the plane in combination with the origin. //Point 1 is the x-axis and point 2 the y-axis. //Each plane is transformed according to the view (axial, coronal and saggital) afterwards. vtkPlane->SetPoint1(1.0, 0.0, 0.0); //P1: (xMax, yMin, depth) vtkPlane->SetPoint2(0.0, 1.0, 0.0); //P2: (xMin, yMax, depth) //these are not the correct values for all slices, only a square plane by now vtkSmartPointer imageMapper = vtkSmartPointer::New(); imageMapper->SetInputConnection(vtkPlane->GetOutputPort()); vtkSmartPointer lookupTable = vtkSmartPointer::New(); //built a default lookuptable lookupTable->SetRampToLinear(); lookupTable->SetSaturationRange( 0.0, 0.0 ); lookupTable->SetHueRange( 0.0, 0.0 ); lookupTable->SetValueRange( 0.0, 1.0 ); lookupTable->Build(); //map all black values to transparent lookupTable->SetTableValue(0, 0.0, 0.0, 0.0, 0.0); lookupTable->SetRange(-255.0, 255.0); //lookupTable->SetRange(-1022.0, 1184.0);//pic3D range vtkSmartPointer texture = vtkSmartPointer::New(); texture->SetInput(slicer->GetOutput()); texture->SetLookupTable(lookupTable); texture->SetMapColorScalarsThroughLookupTable(true); vtkSmartPointer imageActor = vtkSmartPointer::New(); imageActor->SetMapper(imageMapper); imageActor->SetTexture(texture); // Setup renderers vtkSmartPointer renderer = vtkSmartPointer::New(); renderer->AddActor(imageActor); // Setup render window vtkSmartPointer renderWindow = vtkSmartPointer::New(); renderWindow->AddRenderer(renderer); // Setup render window interactor vtkSmartPointer renderWindowInteractor = vtkSmartPointer::New(); vtkSmartPointer style = vtkSmartPointer::New(); renderWindowInteractor->SetInteractorStyle(style); // Render and start interaction renderWindowInteractor->SetRenderWindow(renderWindow); //renderer->AddViewProp(imageActor); renderWindow->Render(); renderWindowInteractor->Start(); // always end with this! /*================ #END vtk render code ================*/ #endif //SHOW_SLICE_IN_RENDER_WINDOW MITK_TEST_END() } diff --git a/Core/Code/Testing/mitkGenericPropertyTest.cpp b/Core/Code/Testing/mitkGenericPropertyTest.cpp index 67da3680ca..c63ae51a40 100644 --- a/Core/Code/Testing/mitkGenericPropertyTest.cpp +++ b/Core/Code/Testing/mitkGenericPropertyTest.cpp @@ -1,109 +1,109 @@ /*=================================================================== 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 "mitkTestingMacros.h" #include "mitkGenericProperty.h" #include "mitkStringProperty.h" #include "mitkProperties.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include #include // call with testValue1 != testValue2 template int TestGenericPropertyForDataType(typename T::ValueType testValue1, typename T::ValueType testValue2, std::string testValue1AsString, std::string testValue2AsString, std::string type) { std::cout << "Testing mitk::GenericProperty<" << type << ">(" << testValue1AsString << ", " << testValue2AsString << ") \n"; typename T::Pointer prop(T::New()); typename T::Pointer prop2(T::New(testValue1)); typename T::Pointer prop3(T::New(testValue2)); unsigned long tBefore = prop->GetMTime(); prop->SetValue(testValue1); unsigned long tAfter = prop->GetMTime(); prop->SetValue(testValue1); unsigned long tAfterAll = prop->GetMTime(); MITK_TEST_CONDITION_REQUIRED(prop->GetValue() == testValue1 && prop->GetValueAsString() == testValue1AsString,"Testing SetValue") MITK_TEST_CONDITION_REQUIRED((*prop == *prop2),"Testing equality operator (operator==)"); prop->SetValue(testValue2); unsigned long tAfterEverything = prop->GetMTime(); std::cout << " Testing MTime correctness when changing property value: "; if (tBefore >= tAfter || tAfterAll != tAfter || tAfterEverything <= tAfterAll) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; prop->SetValue(testValue1); std::cout << " Testing Assignment: "; prop->AssignProperty(*prop3); if ( (! (*prop == *prop3)) || (*prop == *prop2) ) { std::cout << " [FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << std::endl; return EXIT_SUCCESS; } int mitkGenericPropertyTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN(GenericPropertyTest) // testing for some different data types TestGenericPropertyForDataType(1, 2, "1", "2", "int"); TestGenericPropertyForDataType(true, false, "1", "0", "bool"); TestGenericPropertyForDataType(1.0, -1.0, "1", "-1", "float"); TestGenericPropertyForDataType(1.0, -1.0, "1", "-1", "double"); TestGenericPropertyForDataType(std::string("eins"), std::string("zwei"), std::string("eins"), std::string("zwei"), "std::string"); { mitk::Point3D p1; p1[0] = 2.0; p1[1] = 3.0; p1[2] = 4.0; mitk::Point3D p2; p2[0] =-1.0; p2[1] = 2.0; p2[2] = 3.0; TestGenericPropertyForDataType( p1, p2, "[2, 3, 4]", "[-1, 2, 3]", "mitk::Point3D"); } { mitk::Point4D p1; p1[0] = 2.0; p1[1] = 3.0; p1[2] = 4.0; p1[3] =-2.0; mitk::Point4D p2; p2[0] =-1.0; p2[1] = 2.0; p2[2] = 3.0; p2[3] = 5.0; TestGenericPropertyForDataType( p1, p2, "[2, 3, 4, -2]", "[-1, 2, 3, 5]", "mitk::Point4D"); } /* THIS won't compile because of the interface of XMLWriter... that should be reworked perhaps { mitk::Vector2D p1; p1[0] = 2.0; p1[1] = 3.0; mitk::Vector2D p2; p2[0] =-1.0; p2[1] = 2.0; TestGenericPropertyForDataType( p1, p2, "[2, 3]", "[-1, 2]", "mitk::Vector2D"); } */ { mitk::Vector3D p1; p1[0] = 2.0; p1[1] = 3.0; p1[2] = 4.0; mitk::Vector3D p2; p2[0] =-1.0; p2[1] = 2.0; p2[2] = 3.0; TestGenericPropertyForDataType( p1, p2, "[2, 3, 4]", "[-1, 2, 3]", "mitk::Vector3D"); } MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkGeometry3DTest.cpp b/Core/Code/Testing/mitkGeometry3DTest.cpp index 51443d1c33..d642e12452 100644 --- a/Core/Code/Testing/mitkGeometry3DTest.cpp +++ b/Core/Code/Testing/mitkGeometry3DTest.cpp @@ -1,567 +1,567 @@ /*=================================================================== 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 "mitkGeometry3D.h" #include #include #include "mitkRotationOperation.h" #include "mitkInteractionConst.h" #include #include #include "mitkTestingMacros.h" #include -#include +#include bool testGetAxisVectorVariants(mitk::Geometry3D* geometry) { int direction; for(direction=0; direction<3; ++direction) { mitk::Vector3D frontToBack; switch(direction) { case 0: frontToBack = geometry->GetCornerPoint(false, false, false)-geometry->GetCornerPoint(true , false, false); break; //7-3 case 1: frontToBack = geometry->GetCornerPoint(false, false, false)-geometry->GetCornerPoint(false, true , false); break; //7-5 case 2: frontToBack = geometry->GetCornerPoint(false, false, false)-geometry->GetCornerPoint(false , false, true); break; //7-2 } std::cout << "Testing GetAxisVector(int) vs GetAxisVector(bool, bool, bool): "; if(mitk::Equal(geometry->GetAxisVector(direction), frontToBack) == false) { std::cout<<"[FAILED]"<GetAxisVector(direction).GetNorm(), geometry->GetExtentInMM(direction)) == false) { std::cout<<"[FAILED]"<GetOrigin(); mitk::Point3D dummy; MITK_TEST_OUTPUT( << " Testing index->world->index conversion consistency"); geometry3d->WorldToIndex(origin, dummy); geometry3d->IndexToWorld(dummy, dummy); MITK_TEST_CONDITION_REQUIRED(dummy == origin, ""); MITK_TEST_OUTPUT( << " Testing WorldToIndex(origin, mitk::Point3D)==(0,0,0)"); mitk::Point3D globalOrigin; mitk::FillVector3D(globalOrigin, 0,0,0); mitk::Point3D originContinuousIndex; geometry3d->WorldToIndex(origin, originContinuousIndex); MITK_TEST_CONDITION_REQUIRED(originContinuousIndex == globalOrigin, ""); MITK_TEST_OUTPUT( << " Testing WorldToIndex(origin, itk::Index)==(0,0,0)"); itk::Index<3> itkindex; geometry3d->WorldToIndex(origin, itkindex); itk::Index<3> globalOriginIndex; mitk::vtk2itk(globalOrigin, globalOriginIndex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT( << " Testing WorldToIndex(origin-0.5*spacing, itk::Index)==(0,0,0)"); mitk::Vector3D halfSpacingStep = geometry3d->GetSpacing()*0.5; mitk::Matrix3D rotation; mitk::Point3D originOffCenter = origin-halfSpacingStep; geometry3d->WorldToIndex(originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT( << " Testing WorldToIndex(origin+0.5*spacing-eps, itk::Index)==(0,0,0)"); originOffCenter = origin+halfSpacingStep; originOffCenter -= 0.0001; geometry3d->WorldToIndex( originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT( << " Testing WorldToIndex(origin+0.5*spacing, itk::Index)==(1,1,1)"); originOffCenter = origin+halfSpacingStep; itk::Index<3> global111; mitk::FillVector3D(global111, 1,1,1); geometry3d->WorldToIndex( originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == global111, ""); MITK_TEST_OUTPUT( << " Testing WorldToIndex(GetCenter())==BoundingBox.GetCenter: "); mitk::Point3D center = geometry3d->GetCenter(); mitk::Point3D centerContIndex; geometry3d->WorldToIndex(center, centerContIndex); mitk::BoundingBox::ConstPointer boundingBox = geometry3d->GetBoundingBox(); mitk::BoundingBox::PointType centerBounds = boundingBox->GetCenter(); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(centerContIndex,centerBounds), ""); MITK_TEST_OUTPUT( << " Testing GetCenter()==IndexToWorld(BoundingBox.GetCenter): "); center = geometry3d->GetCenter(); mitk::Point3D centerBoundsInWorldCoords; geometry3d->IndexToWorld(centerBounds, centerBoundsInWorldCoords); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(center,centerBoundsInWorldCoords), ""); return EXIT_SUCCESS; } int testIndexAndWorldConsistencyForVectors(mitk::Geometry3D* geometry3d) { MITK_TEST_OUTPUT( << "Testing consistency of index and world coordinate systems for vectors: "); mitk::Vector3D xAxisMM = geometry3d->GetAxisVector(0); mitk::Vector3D xAxisContinuousIndex; mitk::Vector3D xAxisContinuousIndexDeprecated; mitk::Point3D p, pIndex, origin; origin = geometry3d->GetOrigin(); p[0] = xAxisMM[0]; p[1] = xAxisMM[1]; p[2] = xAxisMM[2]; geometry3d->WorldToIndex(p,pIndex); geometry3d->WorldToIndex(xAxisMM, xAxisContinuousIndexDeprecated); geometry3d->WorldToIndex(xAxisMM,xAxisContinuousIndex); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[0] == pIndex[0],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[1] == pIndex[1],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[2] == pIndex[2],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[0] == xAxisContinuousIndexDeprecated[0],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[1] == xAxisContinuousIndexDeprecated[1],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[2] == xAxisContinuousIndexDeprecated[2],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[0] == pIndex[0],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[1] == pIndex[1],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[2] == pIndex[2],""); geometry3d->IndexToWorld(xAxisContinuousIndex,xAxisContinuousIndex); geometry3d->IndexToWorld(xAxisContinuousIndexDeprecated,xAxisContinuousIndexDeprecated); geometry3d->IndexToWorld(pIndex,p); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex == xAxisMM,""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[0] == p[0],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[1] == p[1],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[2] == p[2],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated == xAxisMM,""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[0] == p[0],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[1] == p[1],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[2] == p[2],""); return EXIT_SUCCESS; } #include int testItkImageIsCenterBased() { MITK_TEST_OUTPUT(<< "Testing whether itk::Image coordinates are center-based."); typedef itk::Image ItkIntImage3D; ItkIntImage3D::Pointer itkintimage = ItkIntImage3D::New(); ItkIntImage3D::SizeType size; size.Fill(10); mitk::Point3D origin; mitk::FillVector3D(origin, 2,3,7); itkintimage->Initialize(); itkintimage->SetRegions(size); itkintimage->SetOrigin(origin); std::cout<<"[PASSED]"< originContinuousIndex; itkintimage->TransformPhysicalPointToContinuousIndex(origin, originContinuousIndex); MITK_TEST_CONDITION_REQUIRED(originContinuousIndex == globalOrigin, ""); MITK_TEST_OUTPUT( << " Testing itk::Image::TransformPhysicalPointToIndex(origin)==(0,0,0)"); itk::Index<3> itkindex; itkintimage->TransformPhysicalPointToIndex(origin, itkindex); itk::Index<3> globalOriginIndex; mitk::vtk2itk(globalOrigin, globalOriginIndex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT( << " Testing itk::Image::TransformPhysicalPointToIndex(origin-0.5*spacing)==(0,0,0)"); mitk::Vector3D halfSpacingStep = itkintimage->GetSpacing()*0.5; mitk::Matrix3D rotation; mitk::Point3D originOffCenter = origin-halfSpacingStep; itkintimage->TransformPhysicalPointToIndex(originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT( << " Testing itk::Image::TransformPhysicalPointToIndex(origin+0.5*spacing-eps, itk::Index)==(0,0,0)"); originOffCenter = origin+halfSpacingStep; originOffCenter -= 0.0001; itkintimage->TransformPhysicalPointToIndex( originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT( << " Testing itk::Image::TransformPhysicalPointToIndex(origin+0.5*spacing, itk::Index)==(1,1,1)"); originOffCenter = origin+halfSpacingStep; itk::Index<3> global111; mitk::FillVector3D(global111, 1,1,1); itkintimage->TransformPhysicalPointToIndex( originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == global111, ""); MITK_TEST_OUTPUT( << "=> Yes, itk::Image coordinates are center-based."); return EXIT_SUCCESS; } int testGeometry3D(bool imageGeometry) { // Build up a new image Geometry mitk::Geometry3D::Pointer geometry3d = mitk::Geometry3D::New(); float bounds[ ] = {-10.0, 17.0, -12.0, 188.0, 13.0, 211.0}; MITK_TEST_OUTPUT( << "Initializing"); geometry3d->Initialize(); MITK_TEST_OUTPUT(<< "Setting ImageGeometry to " << imageGeometry); geometry3d->SetImageGeometry(imageGeometry); MITK_TEST_OUTPUT(<< "Setting bounds by SetFloatBounds(): " << bounds); geometry3d->SetFloatBounds(bounds); MITK_TEST_OUTPUT( << "Testing AxisVectors"); if(testGetAxisVectorVariants(geometry3d) == false) return EXIT_FAILURE; if(testGetAxisVectorExtent(geometry3d) == false) return EXIT_FAILURE; MITK_TEST_OUTPUT( << "Creating an AffineTransform3D transform"); mitk::AffineTransform3D::MatrixType matrix; matrix.SetIdentity(); matrix(1,1) = 2; mitk::AffineTransform3D::Pointer transform; transform = mitk::AffineTransform3D::New(); transform->SetMatrix(matrix); MITK_TEST_OUTPUT( << "Testing a SetIndexToWorldTransform"); geometry3d->SetIndexToWorldTransform(transform); MITK_TEST_OUTPUT( << "Testing correctness of value returned by GetSpacing"); const mitk::Vector3D& spacing1 = geometry3d->GetSpacing(); mitk::Vector3D expectedSpacing; expectedSpacing.Fill(1.0); expectedSpacing[1] = 2; if( mitk::Equal(spacing1, expectedSpacing) == false ) { MITK_TEST_OUTPUT( << " [FAILED]"); return EXIT_FAILURE; } MITK_TEST_OUTPUT( << "Testing a Compose(transform)"); geometry3d->Compose(transform); MITK_TEST_OUTPUT( << "Testing correctness of value returned by GetSpacing"); const mitk::Vector3D& spacing2 = geometry3d->GetSpacing(); expectedSpacing[1] = 4; if( mitk::Equal(spacing2, expectedSpacing) == false ) { MITK_TEST_OUTPUT( << " [FAILED]"); return EXIT_FAILURE; } MITK_TEST_OUTPUT( << "Testing correctness of SetSpacing"); mitk::Vector3D newspacing; mitk::FillVector3D(newspacing, 1.5, 2.5, 3.5); geometry3d->SetSpacing(newspacing); const mitk::Vector3D& spacing3 = geometry3d->GetSpacing(); if( mitk::Equal(spacing3, newspacing) == false ) { MITK_TEST_OUTPUT( << " [FAILED]"); return EXIT_FAILURE; } // Seperate Test function for Index and World consistency testIndexAndWorldConsistency(geometry3d); testIndexAndWorldConsistencyForVectors(geometry3d); MITK_TEST_OUTPUT( << "Testing a rotation of the geometry"); double angle = 35.0; mitk::Vector3D rotationVector; mitk::FillVector3D( rotationVector, 1, 0, 0 ); mitk::Point3D center = geometry3d->GetCenter(); mitk::RotationOperation* op = new mitk::RotationOperation( mitk::OpROTATE, center, rotationVector, angle ); geometry3d->ExecuteOperation(op); MITK_TEST_OUTPUT( << "Testing mitk::GetRotation() and success of rotation"); mitk::Matrix3D rotation; mitk::GetRotation(geometry3d, rotation); mitk::Vector3D voxelStep=rotation*newspacing; mitk::Vector3D voxelStepIndex; geometry3d->WorldToIndex(voxelStep, voxelStepIndex); mitk::Vector3D expectedVoxelStepIndex; expectedVoxelStepIndex.Fill(1); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(voxelStepIndex,expectedVoxelStepIndex), ""); delete op; std::cout<<"[PASSED]"<GetImageGeometry() == imageGeometry, ""); //Test if the translate function moves the origin correctly. mitk::Point3D oldOrigin = geometry3d->GetOrigin(); //use some random values for translation mitk::Vector3D translationVector; translationVector.SetElement(0, 17.5f); translationVector.SetElement(1, -32.3f); translationVector.SetElement(2, 4.0f); //compute ground truth mitk::Point3D tmpResult = geometry3d->GetOrigin() + translationVector; geometry3d->Translate(translationVector); MITK_TEST_CONDITION( mitk::Equal( geometry3d->GetOrigin(), tmpResult ), "Testing if origin was translated."); translationVector*=-1; //vice versa geometry3d->Translate(translationVector); MITK_TEST_CONDITION( mitk::Equal( geometry3d->GetOrigin(), oldOrigin ), "Testing if the translation could be done vice versa." ); return EXIT_SUCCESS; } int testGeometryAfterCasting() { // Epsilon. Allowed difference for rotationvalue float eps = 0.0001; // Cast ITK and MITK images and see if geometry stays typedef itk::Image Image2DType; typedef itk::Image Image3DType; // Create 3D ITK Image from Scratch, cast to 3D MITK image, compare Geometries Image3DType::Pointer image3DItk = Image3DType::New(); Image3DType::RegionType myRegion; Image3DType::SizeType mySize; Image3DType::IndexType myIndex; Image3DType::SpacingType mySpacing; Image3DType::DirectionType myDirection, rotMatrixX, rotMatrixY, rotMatrixZ; mySpacing[0] = 31; mySpacing[1] = 0.1; mySpacing[2] = 2.9; myIndex[0] = -15; myIndex[1] = 15; myIndex[2] = 12; mySize[0] = 10; mySize[1] = 2; mySize[2] = 555; myRegion.SetSize( mySize); myRegion.SetIndex( myIndex ); image3DItk->SetSpacing(mySpacing); image3DItk->SetRegions( myRegion); image3DItk->Allocate(); image3DItk->FillBuffer(0); myDirection.SetIdentity(); rotMatrixX.SetIdentity(); rotMatrixY.SetIdentity(); rotMatrixZ.SetIdentity(); mitk::Image::Pointer mitkImage; // direction [row] [coloum] MITK_TEST_OUTPUT( << "Casting a rotated 3D ITK Image to a MITK Image and check if Geometry is still same" ); for (double rotX=0; rotX < (itk::Math::pi*2); rotX+=0.4 ) { // Set Rotation X rotMatrixX[1][1] = cos( rotX ); rotMatrixX[1][2] = -sin( rotX ); rotMatrixX[2][1] = sin( rotX ); rotMatrixX[2][2] = cos( rotX ); for (double rotY=0; rotY < (itk::Math::pi*2); rotY+=0.33 ) { // Set Rotation Y rotMatrixY[0][0] = cos( rotY ); rotMatrixY[0][2] = sin( rotY ); rotMatrixY[2][0] = -sin( rotY ); rotMatrixY[2][2] = cos( rotY ); for (double rotZ=0; rotZ < (itk::Math::pi*2); rotZ+=0.5 ) { // Set Rotation Z rotMatrixZ[0][0] = cos( rotZ ); rotMatrixZ[0][1] = -sin( rotZ ); rotMatrixZ[1][0] = sin( rotZ ); rotMatrixZ[1][1] = cos( rotZ ); // Multiply matrizes myDirection = myDirection * rotMatrixX * rotMatrixY * rotMatrixZ; image3DItk->SetDirection(myDirection); mitk::CastToMitkImage(image3DItk, mitkImage); const mitk::AffineTransform3D::MatrixType& matrix = mitkImage->GetGeometry()->GetIndexToWorldTransform()->GetMatrix(); for (int row=0; row<3; row++) { for (int col=0; col<3; col++) { double mitkValue = matrix[row][col] / mitkImage->GetGeometry()->GetSpacing()[col]; double itkValue = myDirection[row][col]; double diff = mitkValue - itkValue; // if you decrease this value, you can see that there might be QUITE high inaccuracy!!! if (diff > eps) // need to check, how exact it SHOULD be .. since it is NOT EXACT! { std::cout << "Had a difference of : " << diff; std::cout << "Error: Casting altered Geometry!"; std::cout << "ITK Matrix:\n" << myDirection; std::cout << "Mitk Matrix (With Spacing):\n" << matrix; std::cout << "Mitk Spacing: " << mitkImage->GetGeometry()->GetSpacing(); MITK_TEST_CONDITION_REQUIRED(false == true, ""); return false; } } } } } } // Create 2D ITK Image from Scratch, cast to 2D MITK image, compare Geometries Image2DType::Pointer image2DItk = Image2DType::New(); Image2DType::RegionType myRegion2D; Image2DType::SizeType mySize2D; Image2DType::IndexType myIndex2D; Image2DType::SpacingType mySpacing2D; Image2DType::DirectionType myDirection2D, rotMatrix; mySpacing2D[0] = 31; mySpacing2D[1] = 0.1; myIndex2D[0] = -15; myIndex2D[1] = 15; mySize2D[0] = 10; mySize2D[1] = 2; myRegion2D.SetSize( mySize2D); myRegion2D.SetIndex( myIndex2D ); image2DItk->SetSpacing(mySpacing2D); image2DItk->SetRegions( myRegion2D); image2DItk->Allocate(); image2DItk->FillBuffer(0); myDirection2D.SetIdentity(); rotMatrix.SetIdentity(); // direction [row] [coloum] MITK_TEST_OUTPUT( << "Casting a rotated 2D ITK Image to a MITK Image and check if Geometry is still same" ); for (double rotTheta=0; rotTheta < (itk::Math::pi*2); rotTheta+=0.1 ) { // Set Rotation rotMatrix[0][0] = cos(rotTheta); rotMatrix[0][1] = -sin(rotTheta); rotMatrix[1][0] = sin(rotTheta); rotMatrix[1][1] = cos(rotTheta); // Multiply matrizes myDirection2D = myDirection2D * rotMatrix; image2DItk->SetDirection(myDirection2D); mitk::CastToMitkImage(image2DItk, mitkImage); const mitk::AffineTransform3D::MatrixType& matrix = mitkImage->GetGeometry()->GetIndexToWorldTransform()->GetMatrix(); // Compare MITK and ITK matrix for (int row=0; row<3; row++) { for (int col=0; col<3; col++) { double mitkValue = matrix[row][col] / mitkImage->GetGeometry()->GetSpacing()[col]; if ((row == 2) && (col == row)) { if (mitkValue != 1) { MITK_TEST_OUTPUT(<< "After casting a 2D ITK to 3D MITK images, MITK matrix values for 0|2, 1|2, 2|0, 2|1 MUST be 0 and value for 2|2 must be 1"); return false; } } else if ((row == 2) || (col == 2)) { if (mitkValue != 0) { MITK_TEST_OUTPUT(<< "After casting a 2D ITK to 3D MITK images, MITK matrix values for 0|2, 1|2, 2|0, 2|1 MUST be 0 and value for 2|2 must be 1"); return false; } } else { double itkValue = myDirection2D[row][col]; double diff = mitkValue - itkValue; // if you decrease this value, you can see that there might be QUITE high inaccuracy!!! if (diff > eps) // need to check, how exact it SHOULD be .. since it is NOT EXACT! { std::cout << "Had a difference of : " << diff; std::cout << "Error: Casting altered Geometry!"; std::cout << "ITK Matrix:\n" << myDirection2D; std::cout << "Mitk Matrix (With Spacing):\n" << matrix; std::cout << "Mitk Spacing: " << mitkImage->GetGeometry()->GetSpacing(); MITK_TEST_CONDITION_REQUIRED(false == true, ""); return false; } } } } } // THIS WAS TESTED: // 2D ITK -> 2D MITK, // 3D ITK -> 3D MITK, // Still need to test: 2D MITK Image with ADDITIONAL INFORMATION IN MATRIX -> 2D ITK // 1. Possibility: 3x3 MITK matrix can be converted without loss into 2x2 ITK matrix // 2. Possibility: 3x3 MITK matrix can only be converted with loss into 2x2 ITK matrix // .. before implementing this, we wait for further development in geometry classes (e.g. Geoemtry3D::SetRotation(..)) return EXIT_SUCCESS; } int mitkGeometry3DTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN(mitkGeometry3DTest); int result; MITK_TEST_CONDITION_REQUIRED( (result = testItkImageIsCenterBased()) == EXIT_SUCCESS, ""); MITK_TEST_OUTPUT(<< "Running main part of test with ImageGeometry = false"); MITK_TEST_CONDITION_REQUIRED( (result = testGeometry3D(false)) == EXIT_SUCCESS, ""); MITK_TEST_OUTPUT(<< "Running main part of test with ImageGeometry = true"); MITK_TEST_CONDITION_REQUIRED( (result = testGeometry3D(true)) == EXIT_SUCCESS, ""); MITK_TEST_OUTPUT(<< "Running test to see if Casting MITK to ITK and the other way around destroys geometry"); MITK_TEST_CONDITION_REQUIRED( (result = testGeometryAfterCasting()) == EXIT_SUCCESS, ""); MITK_TEST_END(); return EXIT_SUCCESS; } diff --git a/Core/Code/Testing/mitkLogTest.cpp b/Core/Code/Testing/mitkLogTest.cpp index 65fe886844..5a1997524f 100644 --- a/Core/Code/Testing/mitkLogTest.cpp +++ b/Core/Code/Testing/mitkLogTest.cpp @@ -1,286 +1,286 @@ /*=================================================================== 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 "mitkCommon.h" #include "mitkTestingMacros.h" #include -#include +#include #include #include #include /** Documentation * * @brief Objects of this class can start an internal thread by calling the Start() method. * The thread is then logging messages until the method Stop() is called. The class * can be used to test if logging is thread-save by using multiple objects and let * them log simuntanously. */ class mitkTestLoggingThread : public itk::Object { public: mitkClassMacro(mitkTestLoggingThread,itk::Object); mitkNewMacro1Param(mitkTestLoggingThread,itk::MultiThreader::Pointer); int NumberOfMessages; protected: mitkTestLoggingThread(itk::MultiThreader::Pointer MultiThreader) { ThreadID = -1; NumberOfMessages = 0; m_MultiThreader = MultiThreader; } bool LoggingRunning; int ThreadID; itk::MultiThreader::Pointer m_MultiThreader; void LogMessages() { while(LoggingRunning) { MITK_INFO << "Test info stream in thread" << ThreadID << "\n even with newlines"; MITK_WARN << "Test warning stream in thread " << ThreadID <<". " << "Even with a very long text, even without meaning or implied meaning or content, just a long sentence to see whether something has problems with long sentences or output in files or into windows or commandlines or whatever."; MITK_DEBUG << "Test debugging stream in thread " << ThreadID; MITK_ERROR << "Test error stream in thread " << ThreadID; MITK_FATAL << "Test fatal stream in thread " << ThreadID; NumberOfMessages += 5; } } static ITK_THREAD_RETURN_TYPE ThreadStartTracking(void* pInfoStruct) { /* extract this pointer from Thread Info structure */ struct itk::MultiThreader::ThreadInfoStruct * pInfo = (struct itk::MultiThreader::ThreadInfoStruct*)pInfoStruct; if (pInfo == NULL) { return ITK_THREAD_RETURN_VALUE; } if (pInfo->UserData == NULL) { return ITK_THREAD_RETURN_VALUE; } mitkTestLoggingThread *thisthread = (mitkTestLoggingThread*)pInfo->UserData; if (thisthread != NULL) thisthread->LogMessages(); return ITK_THREAD_RETURN_VALUE; } public: int Start() { LoggingRunning = true; this->ThreadID = m_MultiThreader->SpawnThread(this->ThreadStartTracking, this); return ThreadID; } void Stop() { LoggingRunning = false; } }; /** Documentation * * @brief This class holds static test methods to sturcture the test of the mitk logging mechanism. */ class mitkLogTestClass { public: static void TestSimpleLog() { bool testSucceded = true; try { MITK_INFO << "Test info stream."; MITK_WARN << "Test warning stream."; MITK_DEBUG << "Test debugging stream."; //only activated if cmake variable is on! //so no worries if you see no output for this line MITK_ERROR << "Test error stream."; MITK_FATAL << "Test fatal stream."; } catch(mitk::Exception e) { testSucceded = false; } MITK_TEST_CONDITION_REQUIRED(testSucceded,"Test logging streams."); } static void TestObjectInfoLogging() { bool testSucceded = true; try { int i = 123; float f = .32234; double d = 123123; std::string testString = "testString"; std::stringstream testStringStream; testStringStream << "test" << "String" << "Stream"; mitk::Point3D testMitkPoint; testMitkPoint.Fill(2); MITK_INFO << i; MITK_INFO << f; MITK_INFO << d; MITK_INFO << testString; MITK_INFO << testStringStream; MITK_INFO << testMitkPoint; } catch(mitk::Exception e) { testSucceded = false; } MITK_TEST_CONDITION_REQUIRED(testSucceded,"Test logging of object information."); } static void TestThreadSaveLog(bool toFile) { bool testSucceded = true; try { if (toFile) { std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory() + "/testthreadlog.log"; itksys::SystemTools::RemoveFile(filename.c_str()); // remove old file, we do not want to append to large files mitk::LoggingBackend::SetLogFile(filename.c_str()); } unsigned int numberOfThreads = 20; unsigned int threadRuntimeInMilliseconds = 2000; std::vector threadIDs; std::vector threads; itk::MultiThreader::Pointer multiThreader = itk::MultiThreader::New(); for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx) { //initialize threads... mitkTestLoggingThread::Pointer newThread = mitkTestLoggingThread::New(multiThreader); threads.push_back(newThread); std::cout << "Created " << threadIdx << ". thread." << std::endl; } for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx) { //start them std::cout << "Start " << threadIdx << ". thread." << std::endl; threadIDs.push_back( threads[threadIdx]->Start() ); std::cout << threadIdx << ". thread has ID " << threadIDs[threadIdx] << std::endl; } //wait for some time (milliseconds) itksys::SystemTools::Delay( threadRuntimeInMilliseconds ); for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx) { //stop them std::cout << "Stop " << threadIdx << ". thread." << std::endl; threads[threadIdx]->Stop(); } for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx) { //Wait for all threads to end multiThreader->TerminateThread(threadIDs[threadIdx]); std::cout << "Terminated " << threadIdx << ". thread (" << threads[threadIdx]->NumberOfMessages << " messages)." << std::endl; } } catch(std::exception e) { MITK_ERROR << "exception during 'TestThreadSaveLog': "<GetOptionDirectory() + "/testlog.log"; mitk::LoggingBackend::SetLogFile(filename.c_str()); MITK_INFO << "Test logging to default filename: " << mitk::LoggingBackend::GetLogFile(); MITK_TEST_CONDITION_REQUIRED(itksys::SystemTools::FileExists(filename.c_str()),"Testing if log file exists."); //TODO delete log file? } static void TestAddAndRemoveBackends() { mbilog::BackendCout myBackend = mbilog::BackendCout(); mbilog::RegisterBackend(&myBackend); MITK_INFO << "Test logging"; mbilog::UnregisterBackend(&myBackend); //if no error occured until now, everything is ok MITK_TEST_CONDITION_REQUIRED(true,"Test add/remove logging backend."); } static void TestDefaultBackend() { //not possible now, because we cannot unregister the mitk logging backend in the moment. If such a method is added to mbilog utility one may add this test. } }; int mitkLogTest(int /* argc */, char* /*argv*/[]) { // always start with this! MITK_TEST_BEGIN("Log") MITK_TEST_OUTPUT(<<"TESTING ALL LOGGING OUTPUTS, ERROR MESSAGES ARE ALSO TESTED AND NOT MEANING AN ERROR OCCURED!") mitkLogTestClass::TestSimpleLog(); mitkLogTestClass::TestObjectInfoLogging(); mitkLogTestClass::TestLoggingToFile(); mitkLogTestClass::TestAddAndRemoveBackends(); mitkLogTestClass::TestThreadSaveLog( false ); // false = to console mitkLogTestClass::TestThreadSaveLog( true ); // true = to file // TODO actually test file somehow? // always end with this! MITK_TEST_END() } diff --git a/Core/Code/Testing/mitkPointSetTest.cpp b/Core/Code/Testing/mitkPointSetTest.cpp index 98436637cc..fc7e2419c8 100644 --- a/Core/Code/Testing/mitkPointSetTest.cpp +++ b/Core/Code/Testing/mitkPointSetTest.cpp @@ -1,666 +1,666 @@ /*=================================================================== 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 "mitkTestingMacros.h" #include -#include +#include #include #include #include class mitkPointSetTestClass { public: static void TestGetITKPointSet(mitk::PointSet *pointSet) { //try to get the itkPointSet mitk::PointSet::DataType::Pointer itkdata = NULL; itkdata = pointSet->GetPointSet(); MITK_TEST_CONDITION( itkdata.IsNotNull(), "try to get the itkPointSet from a newly created PointSet" ) } static void TestGetSizeIsZero(mitk::PointSet *pointSet) { //fresh PointSet has to be empty! MITK_TEST_CONDITION( pointSet->GetSize() == 0, "check if the PointSet size is 0 " ) } static void TestIsEmpty(mitk::PointSet *pointSet) { MITK_TEST_CONDITION(pointSet->IsEmptyTimeStep(0), "check if the PointSet is empty" ) } static void TestCreateOperationAndAddPoint(mitk::PointSet *pointSet) { int id = 0; mitk::Point3D point; point.Fill(1); mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpINSERT, point, id); pointSet->ExecuteOperation(doOp); MITK_TEST_CONDITION( pointSet->GetSize()==1 && pointSet->IndexExists(id), "check if added points exists" ) delete doOp; mitk::Point3D tempPoint; tempPoint.Fill(0); tempPoint = pointSet->GetPoint(id); MITK_TEST_CONDITION( point == tempPoint, "check if added point contains real value" ) } static void TestAddSecondPoint(mitk::PointSet *pointSet) { //add a point directly int id=0; mitk::Point3D point; mitk::FillVector3D(point, 1.0, 2.0, 3.0); ++id; pointSet->GetPointSet()->GetPoints()->InsertElement(id, point); MITK_TEST_CONDITION( pointSet->GetSize()==2 ||pointSet->IndexExists(id), "check if added points exists" ) mitk::Point3D tempPoint; tempPoint.Fill(0); tempPoint = pointSet->GetPoint(id); MITK_TEST_CONDITION( point == tempPoint, "check if added point contains real value" ) } static void TestIsNotEmpty(mitk::PointSet *pointSet) { //PointSet can not be empty! MITK_TEST_CONDITION( !pointSet->IsEmptyTimeStep(0), "check if the PointSet is not empty " ) /* std::cout << "check if the PointSet is not empty "; if (pointSet->IsEmpty(0)) { std::cout<<"[FAILED]"<GetPoint(1); pointSet->SwapPointPosition(1, true); tempPoint = pointSet->GetPoint(0); MITK_TEST_CONDITION( point == tempPoint, "check SwapPointPosition upwards" ) /* if(point != tempPoint) { std::cout<<"[FAILED]"<SwapPointPosition(0, true)==false, "check SwapPointPosition upwards not possible" ) /* if(pointSet->SwapPointPosition(0, true)) { std::cout<<"[FAILED]"<GetPoint(0); pointSet->SwapPointPosition(0, false); tempPoint = pointSet->GetPoint(1); MITK_TEST_CONDITION( point == tempPoint, "check SwapPointPosition down" ) /* if(point != tempPoint) { std::cout<<"[FAILED]"<SetPoint(id, point); //Check SwapPointPosition downwards not possible MITK_TEST_CONDITION(!pointSet2->SwapPointPosition(id, false), "check SwapPointPosition downwards not possible" ) /* if(pointSet->SwapPointPosition(1, false)) { std::cout<<"[FAILED]"<ExecuteOperation(doOp); tempPoint = pointSet->GetPoint(id); MITK_TEST_CONDITION(tempPoint == point1 , "check PointOperation OpMove " ) delete doOp; /* if (tempPoint != point1) { std::cout<<"[FAILED]"<GetPoint(id); mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpREMOVE, point, id); pointSet->ExecuteOperation(doOp); tempPoint = pointSet->GetPoint(id); MITK_TEST_CONDITION(!pointSet->IndexExists(id) , "check PointOperation OpREMOVE " ) delete doOp; /* if(pointSet->IndexExists(id)) { std::cout<<"[FAILED]"<ExecuteOperation(doOp); MITK_TEST_CONDITION(pointSet->GetSelectInfo(4) , "check PointOperation OpSELECTPOINT " ) delete doOp; /* if (!pointSet->GetSelectInfo(4)) { std::cout<<"[FAILED]"<GetNumberOfSelected() == 1 , "check GetNumeberOfSelected " ) /* if(pointSet->GetNumberOfSelected() != 1) { std::cout<<"[FAILED]"<SearchSelectedPoint() == 4 , "check SearchSelectedPoint " ) /* if( pointSet->SearchSelectedPoint() != 4) { std::cout<<"[FAILED]"<ExecuteOperation(doOp); MITK_TEST_CONDITION(!pointSet->GetSelectInfo(4) , "check PointOperation OpDESELECTPOINT " ) MITK_TEST_CONDITION(pointSet->GetNumberOfSelected() == 0 , "check GetNumeberOfSelected " ) delete doOp; /* if (pointSet->GetSelectInfo(4)) { std::cout<<"[FAILED]"<GetNumberOfSelected() != 0) { std::cout<<"[FAILED]"<GetPoint(id); mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVEPOINTUP, point4, id); pointSet->ExecuteOperation(doOp); tempPoint = pointSet->GetPoint(id-1); MITK_TEST_CONDITION(tempPoint == point , "check PointOperation OpMOVEPOINTUP " ) delete doOp; /* if (tempPoint != point) { std::cout<<"[FAILED]"<GetPoint(id); mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVEPOINTDOWN, point2, id); pointSet->ExecuteOperation(doOp); tempPoint = pointSet->GetPoint(id+1); MITK_TEST_CONDITION(tempPoint == point , "check PointOperation OpMOVEPOINTDOWN " ) delete doOp; /* if (tempPoint != point) { std::cout<<"[FAILED]"<SetSelectInfo(2, true); MITK_TEST_CONDITION(pointSet->GetSelectInfo(2) , "check SetSelectInfo" ) /* if (!pointSet->GetSelectInfo(2)) { std::cout<<"[FAILED]"<SetPoint(5, point5, mitk::PTEDGE ); tempPoint = pointSet->GetPoint(5); MITK_TEST_CONDITION(tempPoint == point5, "check InsertPoint with PointSpecification" ) /* if (tempPoint != point5) { std::cout<<"[FAILED]"<GetPointIfExists(5, &tmpPoint); MITK_TEST_CONDITION(tmpPoint == point5, "check GetPointIfExists: " ) /* if (tmpPoint != point5) { std::cout<<"[FAILED]"<InsertPoint(10, p10); pointSet->InsertPoint(11, p11); pointSet->InsertPoint(12, p12); MITK_TEST_CONDITION((pointSet->IndexExists(10) == true) || (pointSet->IndexExists(11) == true) || (pointSet->IndexExists(12) == true), "add points with id 10, 11, 12: " ) //check OpREMOVE ExecuteOperation int id = 11; mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpREMOVE, point, id); pointSet->ExecuteOperation(doOp); MITK_TEST_CONDITION(!pointSet->IndexExists(id), "remove point id 11: ") /* if(pointSet->IndexExists(id)) { std::cout<<"[FAILED]"<ExecuteOperation(doOp); delete doOp; //check OpMOVEPOINTUP ExecuteOperation doOp = new mitk::PointOperation(mitk::OpMOVEPOINTUP, p12, 12); pointSet->ExecuteOperation(doOp); delete doOp; mitk::PointSet::PointType newP10 = pointSet->GetPoint(10); mitk::PointSet::PointType newP12 = pointSet->GetPoint(12); MITK_TEST_CONDITION(((newP10 == p12) && (newP12 == p10)) == true, "check PointOperation OpMOVEPOINTUP for point id 12:" ) //check OpMOVEPOINTDOWN ExecuteOperation doOp = new mitk::PointOperation(mitk::OpMOVEPOINTDOWN, p10, 10); pointSet->ExecuteOperation(doOp); delete doOp; newP10 = pointSet->GetPoint(10); newP12 = pointSet->GetPoint(12); MITK_TEST_CONDITION(((newP10 == p10) && (newP12 == p12)) == true, "check PointOperation OpMOVEPOINTDOWN for point id 10: ") } static void TestOpMovePointUpOnFirstPoint(mitk::PointSet *pointSet) { //check OpMOVEPOINTUP on first point ExecuteOperation mitk::PointSet::PointType p1 = pointSet->GetPoint(1); mitk::PointSet::PointType p2 = pointSet->GetPoint(2); mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVEPOINTUP, p1, 1); pointSet->ExecuteOperation(doOp); delete doOp; mitk::PointSet::PointType newP1 = pointSet->GetPoint(1); mitk::PointSet::PointType newP2 = pointSet->GetPoint(2); MITK_TEST_CONDITION(((newP1 == p1) && (newP2 == p2)) == true, "check PointOperation OpMOVEPOINTUP for point id 1: ") /* if (((newP1 == p1) && (newP2 == p2)) == false) { std::cout<<"[FAILED]"<GetPointSet()->GetPoints(); mitk::PointSet::PointDataContainer* pd = ps->GetPointSet()->GetPointData(); MITK_TEST_CONDITION_REQUIRED(pc->Size() == pd->Size(), "PointContainer and PointDataContainer have same size"); mitk::PointSet::PointsContainer::ConstIterator pIt = pc->Begin(); mitk::PointSet::PointDataContainer::ConstIterator dIt = pd->Begin(); bool failed = false; for (; pIt != pc->End(); ++pIt, ++dIt) if (pIt->Index() != dIt->Index()) { failed = true; break; } MITK_TEST_CONDITION(failed == false, "Indices in PointContainer and PointDataContainer are equal"); } }; int mitkPointSetTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN("PointSet") //Create PointSet mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); MITK_TEST_CONDITION_REQUIRED(pointSet.IsNotNull(),"Testing instantiation") mitkPointSetTestClass::TestGetITKPointSet(pointSet); mitkPointSetTestClass::TestGetSizeIsZero(pointSet); mitkPointSetTestClass::TestIsEmpty(pointSet); mitkPointSetTestClass::TestCreateOperationAndAddPoint(pointSet); mitk::Point3D point2, point3, point4; point2.Fill(3); point3.Fill(4); point4.Fill(5); pointSet->InsertPoint(2,point2); pointSet->InsertPoint(3,point3); pointSet->InsertPoint(4,point4); mitkPointSetTestClass::TestAddSecondPoint(pointSet); mitkPointSetTestClass::TestIsNotEmpty(pointSet); mitkPointSetTestClass::TestSwapPointPositionUpwards(pointSet); mitkPointSetTestClass::TestSwapPointPositionUpwardsNotPossible(pointSet); mitkPointSetTestClass::TestSwapPointPositionDownwards(pointSet); mitkPointSetTestClass::TestSwapPointPositionDownwardsNotPossible(pointSet); mitkPointSetTestClass::TestPointOperationOpMove(pointSet); mitkPointSetTestClass::TestPointOperationOpRemove(pointSet); mitkPointSetTestClass::TestPointOperationOpSelectPoint(pointSet); mitkPointSetTestClass::TestGetNumberOfSelected(pointSet); mitkPointSetTestClass::TestSearchSelectedPoint(pointSet); mitkPointSetTestClass::TestOpDeselectPoint(pointSet); mitkPointSetTestClass::TestOpMovePointUp(pointSet); mitkPointSetTestClass::TestOpMovePointDown(pointSet); mitkPointSetTestClass::TestSetSelectInfo(pointSet); mitkPointSetTestClass::TestInsertPointWithPointSpecification(pointSet); mitkPointSetTestClass::TestGetPointIfExists(pointSet); mitkPointSetTestClass::TestCreateHoleInThePointIDs(pointSet); mitkPointSetTestClass::TestOpMovePointUpOnFirstPoint(pointSet); MITK_TEST_OUTPUT(<< "Test InsertPoint(), SetPoint() and SwapPointPosition()"); mitk::PointSet::PointType point; mitk::FillVector3D(point, 2.2, 3.3, -4.4); /* call everything that might modify PointContainer and PointDataContainer */ pointSet->InsertPoint(17, point); pointSet->SetPoint(4, point); pointSet->SetPoint(7, point); pointSet->SetPoint(2, point); pointSet->SwapPointPosition(7, true); pointSet->SwapPointPosition(3, true); pointSet->SwapPointPosition(2, false); mitkPointSetTestClass::TestPointContainerPointDataContainer(pointSet); MITK_TEST_OUTPUT(<< "Test OpREMOVE"); mitk::PointOperation op1(mitk::OpREMOVE, mitk::Point3D(), 2); // existing index pointSet->ExecuteOperation(&op1); mitk::PointOperation op1b(mitk::OpREMOVE, mitk::Point3D(), 112); // non existing index pointSet->ExecuteOperation(&op1b); mitkPointSetTestClass::TestPointContainerPointDataContainer(pointSet); MITK_TEST_OUTPUT(<< "Test OpMove"); mitk::PointOperation op2(mitk::OpMOVE, mitk::Point3D(), 4); // existing index pointSet->ExecuteOperation(&op2); mitk::PointOperation op3(mitk::OpMOVE, mitk::Point3D(), 34); // non existing index pointSet->ExecuteOperation(&op3); mitkPointSetTestClass::TestPointContainerPointDataContainer(pointSet); MITK_TEST_OUTPUT(<< "Test OpINSERT"); mitk::PointOperation op4(mitk::OpINSERT, mitk::Point3D(), 38); // non existing index pointSet->ExecuteOperation(&op4); mitk::PointOperation op5(mitk::OpINSERT, mitk::Point3D(), 17); // existing index pointSet->ExecuteOperation(&op5); mitkPointSetTestClass::TestPointContainerPointDataContainer(pointSet); pointSet = mitk::PointSet::New(); pointSet->Expand(3); mitk::Point3D new0, new1, new2; new0.Fill(0); new1.Fill(1); new2.Fill(2); pointSet->InsertPoint(5,new0, mitk::PTCORNER,0); pointSet->InsertPoint(112,new1,0); pointSet->InsertPoint(2,new2,0); pointSet->InsertPoint(2,new0,1); pointSet->InsertPoint(1,new1,1); pointSet->InsertPoint(0,new2,1); pointSet->InsertPoint(0,new0,2); pointSet->InsertPoint(2,new1,2); pointSet->InsertPoint(1,new2,2); MITK_TEST_OUTPUT( << "... pointset ts: " << pointSet->GetTimeSteps() ) mitk::PointSet::Pointer clonePS = pointSet->Clone(); MITK_TEST_OUTPUT( << "... clone pointset ts: " << clonePS->GetTimeSteps() ) for (unsigned int t=0; t< pointSet->GetTimeSteps(); t++) { MITK_TEST_OUTPUT( << "testing timestep: " << t ) MITK_TEST_CONDITION_REQUIRED(pointSet->GetSize(t) == clonePS->GetSize(t), "Clone has same size") // test for equal point coordinates for (mitk::PointSet::PointsConstIterator i = pointSet->Begin(), j = clonePS->Begin(); i != pointSet->End() && j != clonePS->End(); ++i, ++j) { MITK_TEST_CONDITION_REQUIRED(i.Index() == j.Index() && mitk::Equal(i.Value(),j.Value()), "Cloned PS and PS have same points") } // test for equal point data mitk::PointSet::PointDataContainer* pointDataCont = pointSet->GetPointSet(t)->GetPointData(); mitk::PointSet::PointDataContainer* clonePointDataCont = clonePS->GetPointSet(t)->GetPointData(); MITK_TEST_CONDITION_REQUIRED(pointDataCont && clonePointDataCont, "Valid point data container") MITK_TEST_CONDITION_REQUIRED(pointDataCont->Size() == clonePointDataCont->Size(), "Cloned point data container has same size") for (mitk::PointSet::PointDataConstIterator i = pointDataCont->Begin(), j = clonePointDataCont->Begin(); i != pointDataCont->End() && j != clonePointDataCont->End(); ++i, ++j) { MITK_TEST_CONDITION_REQUIRED(i.Index() == j.Index() && i.Value() == j.Value(), "Cloned PS and PS have same point data") } } mitkPointSetTestClass::TestIsNotEmpty(clonePS); MITK_TEST_CONDITION_REQUIRED(clonePS->GetPointSetSeriesSize() == pointSet->GetPointSetSeriesSize(), "Testing cloned point set's size!"); MITK_TEST_CONDITION_REQUIRED(clonePS.GetPointer() != pointSet.GetPointer(), "Testing that the clone is not the source PS!"); MITK_TEST_CONDITION_REQUIRED(clonePS->GetGeometry()->GetCenter() == pointSet->GetGeometry()->GetCenter() , "Testing if the geometry is cloned correctly!"); MITK_TEST_CONDITION_REQUIRED(clonePS->GetPropertyList()->GetMap()->size() == pointSet->GetPropertyList()->GetMap()->size() , "Testing if the property list is cloned correctly!"); // Also testing, that clone is independent from original mitk::Point3D p, p2; p.Fill(42); p2.Fill(84); clonePS->InsertPoint(0,p); pointSet->InsertPoint(0,p2); p = clonePS->GetPoint(0); p2 = pointSet->GetPoint(0); MITK_TEST_CONDITION_REQUIRED(p != p2, "Testing that the clone is independent from source!"); MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkSurfaceTest.cpp b/Core/Code/Testing/mitkSurfaceTest.cpp index 0aae3828e0..ca71fdc399 100644 --- a/Core/Code/Testing/mitkSurfaceTest.cpp +++ b/Core/Code/Testing/mitkSurfaceTest.cpp @@ -1,151 +1,151 @@ /*=================================================================== 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 "mitkSurface.h" #include "mitkCommon.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkTestingMacros.h" #include "mitkTimeSlicedGeometry.h" #include "vtkPolyData.h" #include "vtkSphereSource.h" #include int mitkSurfaceTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN("Surface"); mitk::Surface::Pointer surface = mitk::Surface::New(); MITK_TEST_CONDITION_REQUIRED( surface.GetPointer(), "Testing initialization!" ); mitk::Surface::Pointer cloneSurface = surface->Clone(); MITK_TEST_CONDITION_REQUIRED( cloneSurface.GetPointer(), "Testing clone surface initialization!" ); vtkSphereSource* sphereSource = vtkSphereSource::New(); sphereSource->SetCenter(0,0,0); sphereSource->SetRadius(5.0); sphereSource->SetThetaResolution(10); sphereSource->SetPhiResolution(10); sphereSource->Update(); vtkPolyData* polys = sphereSource->GetOutput(); MITK_TEST_CONDITION_REQUIRED(surface->GetVtkPolyData() == NULL, "Testing initial state of vtkPolyData"); surface->SetVtkPolyData( polys ); sphereSource->Delete(); MITK_TEST_CONDITION_REQUIRED(surface->GetVtkPolyData()!= NULL, "Testing set vtkPolyData"); cloneSurface= NULL; cloneSurface = surface->Clone(); MITK_TEST_CONDITION_REQUIRED(cloneSurface->GetVtkPolyData()!= NULL, "Testing set vtkPolyData of cloned surface!"); cloneSurface = NULL; vtkFloatingPointType bounds[6] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; polys->ComputeBounds(); polys->GetBounds( bounds ); surface->UpdateOutputInformation(); surface->SetRequestedRegionToLargestPossibleRegion(); mitk::BoundingBox* bb = const_cast(surface->GetGeometry()->GetBoundingBox()); mitk::BoundingBox::BoundsArrayType surfBounds = bb->GetBounds(); bool passed = false; if ( bounds[0] == surfBounds[0] && bounds[1] == surfBounds[1] && bounds[2] == surfBounds[2] && bounds[3] == surfBounds[3] && bounds[4] == surfBounds[4] && bounds[5] == surfBounds[5] ) { passed = true; } MITK_TEST_CONDITION_REQUIRED(passed, "Testing GetBoundingBox()!"); surface->Expand(5); surface->Update(); surface->SetRequestedRegionToLargestPossibleRegion(); mitk::Surface::RegionType requestedRegion = surface->GetRequestedRegion(); MITK_TEST_CONDITION_REQUIRED(requestedRegion.GetSize(3) == 5, "Testing mitk::Surface::Expand( timesteps ): "); vtkFloatingPointType boundsMat[5][6]; for (int i=0;i<5;i++) { vtkSphereSource* sphereSource = vtkSphereSource::New(); sphereSource->SetCenter(0,0,0); sphereSource->SetRadius(1.0 * (i+1.0)); sphereSource->SetThetaResolution(10); sphereSource->SetPhiResolution(10); sphereSource->Update(); sphereSource->GetOutput()->ComputeBounds(); sphereSource->GetOutput()->GetBounds( boundsMat[i] ); surface->SetVtkPolyData( sphereSource->GetOutput(),i ); sphereSource->Delete(); } surface->UpdateOutputInformation(); surface->SetRequestedRegionToLargestPossibleRegion(); passed = true; for (int i=0;i<5;i++) { mitk::BoundingBox::BoundsArrayType surfBounds = (const_cast(surface->GetTimeSlicedGeometry()->GetGeometry3D(i)->GetBoundingBox()))->GetBounds(); if ( boundsMat[i][0] != surfBounds[0] || boundsMat[i][1] != surfBounds[1] || boundsMat[i][2] != surfBounds[2] || boundsMat[i][3] != surfBounds[3] || boundsMat[i][4] != surfBounds[4] || boundsMat[i][5] != surfBounds[5] ) { passed = false; break; } } MITK_TEST_CONDITION_REQUIRED(passed, "Testing mitk::Surface::Testing 4D surface data creation!" ); const mitk::TimeSlicedGeometry* inputTimeGeometry = surface->GetUpdatedTimeSlicedGeometry(); int time = 3; int timestep=0; timestep = inputTimeGeometry->MSToTimeStep( time ); MITK_TEST_CONDITION_REQUIRED(time == timestep, "Testing correctness of geometry for surface->GetUpdatedTimeSlicedGeometry()!"); sphereSource = vtkSphereSource::New(); sphereSource->SetCenter(0,0,0); sphereSource->SetRadius( 100.0 ); sphereSource->SetThetaResolution(10); sphereSource->SetPhiResolution(10); sphereSource->Update(); surface->SetVtkPolyData( sphereSource->GetOutput(), 3 ); sphereSource->Delete(); inputTimeGeometry = surface->GetUpdatedTimeSlicedGeometry(); time = 3; timestep=0; timestep = inputTimeGeometry->MSToTimeStep( time ); MITK_TEST_CONDITION_REQUIRED(time == timestep, "Explicitly changing the data of timestep 3 and checking for timebounds correctness of surface's geometry again!"); unsigned int numberoftimesteps = surface->GetTimeSteps(); mitk::Surface::Pointer dummy = mitk::Surface::New(); dummy->Graft(surface); MITK_TEST_CONDITION_REQUIRED( dummy->GetVtkPolyData() != NULL, "Testing copying a Surface with Graft()!"); MITK_TEST_CONDITION_REQUIRED( dummy->GetTimeSteps() == numberoftimesteps, "orig-numberofTimeSteps:" << numberoftimesteps << " copy-numberofTimeSteps:" << dummy->GetTimeSteps()); surface = NULL; MITK_TEST_CONDITION_REQUIRED( surface.IsNull(), "Testing destruction of surface!"); MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkSurfaceToSurfaceFilterTest.cpp b/Core/Code/Testing/mitkSurfaceToSurfaceFilterTest.cpp index f5c8e15ddd..b0a014c24b 100644 --- a/Core/Code/Testing/mitkSurfaceToSurfaceFilterTest.cpp +++ b/Core/Code/Testing/mitkSurfaceToSurfaceFilterTest.cpp @@ -1,122 +1,122 @@ /*=================================================================== 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 "mitkSurface.h" #include "mitkSurfaceToSurfaceFilter.h" #include "mitkCommon.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkTimeSlicedGeometry.h" #include "vtkPolyData.h" #include "vtkSphereSource.h" #include int mitkSurfaceToSurfaceFilterTest(int /*argc*/, char* /*argv*/[]) { mitk::Surface::Pointer surface; surface = mitk::Surface::New(); vtkSphereSource* sphereSource = vtkSphereSource::New(); sphereSource->SetCenter(0,0,0); sphereSource->SetRadius(5.0); sphereSource->SetThetaResolution(10); sphereSource->SetPhiResolution(10); sphereSource->Update(); vtkPolyData* polys = sphereSource->GetOutput(); surface->SetVtkPolyData( polys ); sphereSource->Delete(); mitk::SurfaceToSurfaceFilter::Pointer filter = mitk::SurfaceToSurfaceFilter::New(); std::cout << "Testing mitk::SurfaceToSurfaceFilter::SetInput() and ::GetNumberOfInputs() : " ; filter->SetInput( surface ); if ( filter->GetNumberOfInputs() < 1 ) { std::cout<<"[FAILED] : zero inputs set "<GetInput() != surface ) { std::cout<<"[FAILED] : GetInput does not return correct input. "<GetInput(5) != NULL ) { std::cout<<"[FAILED] : GetInput returns inputs that were not set. "< is NULL" << std::endl; std::cout << "Testing whether Output is created correctly : " << std::endl; if ( filter->GetNumberOfOutputs() != filter->GetNumberOfInputs() ) { std::cout <<"[FAILED] : number of outputs != number of inputs" << std::endl; return EXIT_FAILURE; } std::cout << "[SUCCESS] : number of inputs == number of outputs." << std::endl; mitk::Surface::Pointer outputSurface = filter->GetOutput(); if ( outputSurface->GetVtkPolyData()->GetNumberOfPolys() != surface->GetVtkPolyData()->GetNumberOfPolys() ) { std::cout << "[FAILED] : number of Polys in PolyData of output != number of Polys in PolyData of input" << std::endl; return EXIT_FAILURE; } std::cout << "[SUCCESS] : number of Polys in PolyData of input and output are identical." << std::endl; filter->Update(); outputSurface = filter->GetOutput(); if ( outputSurface->GetSizeOfPolyDataSeries() != surface->GetSizeOfPolyDataSeries() ) { std::cout << "[FAILED] : number of PolyDatas in PolyDataSeries of output != number of PolyDatas of input" << std::endl; return EXIT_FAILURE; } std::cout << "[SUCCESS] : Size of PolyDataSeries of input and output are identical." << std::endl; //std::cout << "Testing RemoveInputs() : " << std::endl; //unsigned int numOfInputs = filter->GetNumberOfInputs(); //filter->RemoveInputs( mitk::Surface::New() ); //if ( filter->GetNumberOfInputs() != numOfInputs ) //{ // std::cout << "[FAILED] : input was removed that was not set." << std::endl; // return EXIT_FAILURE; //} //std::cout << "[SUCCESS] : no input was removed that was not set." << std::endl; //filter->RemoveInputs( surface ); //if ( filter->GetNumberOfInputs() != 0 ) //{ // std::cout << "[FAILED] : existing input was not removed correctly." << std::endl; // return EXIT_FAILURE; //} //std::cout << "[SUCCESS] : existing input was removed correctly." << std::endl; std::cout<<"[TEST DONE]"< using namespace mitk; static vtkSmartPointer a_vtkPoints = vtkSmartPointer::New(); static const ScalarType originalValues[] = {1.0, 2.0, 3.0}; static const ScalarType valuesToCopy[] = {4.0, 5.0, 6.0}; static void Setup(void) { a_vtkPoints->Initialize(); } static void Test_Mitk2Itk_PointCompatibility() { Setup(); itk::Point itkPoint3D = originalValues; mitk::Point3D point3D = valuesToCopy; itkPoint3D = point3D; MITK_TEST_CONDITION(itkPoint3D == point3D, "mitk point assigned to itk point") MITK_TEST_CONDITION(itkPoint3D == valuesToCopy, "correct values were assigned") } static void Test_Itk2Mitk_PointCompatibility() { Setup(); mitk::Point3D point3D = originalValues; itk::Point itkPoint3D = valuesToCopy; point3D = itkPoint3D; MITK_TEST_CONDITION(point3D == itkPoint3D, "itk point assigned to mitk point") MITK_TEST_CONDITION(point3D == valuesToCopy, "correct values were assigned") } static void Test_Vtk2Mitk_PointCompatibility() { Setup(); mitk::Point3D point3D = originalValues; a_vtkPoints->InsertNextPoint(valuesToCopy); double vtkPoint[3]; a_vtkPoints->GetPoint(0, vtkPoint); point3D = vtkPoint; MITK_TEST_CONDITION(point3D == vtkPoint, "vtkPoint assigned to mitk point") MITK_TEST_CONDITION(point3D == valuesToCopy, "correct values were assigned") } static void Test_Mitk2Vtk_PointCompatibility() { Setup(); double vtkPoint[3]; mitk::Point3D point3D = valuesToCopy; //a_vtkPoints->InsertNextPoint(point3D.GetAsArray()); // a_vtkPoints->GetPoint(0, vtkPoint); MITK_TEST_CONDITION(point3D == vtkPoint, "MITK point assigned to VTK point") MITK_TEST_CONDITION(Equal(vtkPoint[0], valuesToCopy[0]) && Equal(vtkPoint[1], valuesToCopy[1]) && Equal(vtkPoint[2], valuesToCopy[2]), "correct values were assigned") } static void Test_Mitk2Pod_PointCompatibility() { ScalarType podPoint[] = {1.0, 2.0, 3.0}; mitk::Point3D point3D = valuesToCopy; point3D.CopyToArray(podPoint); MITK_TEST_CONDITION(point3D == podPoint, "MITK point assigned to POD point") MITK_TEST_CONDITION(Equal(podPoint[0], valuesToCopy[0]) && Equal(podPoint[1], valuesToCopy[1]) && Equal(podPoint[2], valuesToCopy[2]), "correct values were assigned") } static void Test_Pod2Mitk_PointCompatibility() { mitk::Point3D point3D = originalValues; ScalarType podPoint[] = {4.0, 5.0, 6.0}; point3D = podPoint; MITK_TEST_CONDITION(point3D == podPoint, "POD point assigned to MITK point") MITK_TEST_CONDITION(point3D == valuesToCopy, "correct values were assigned") } template< class T, unsigned int NVectorDimension> itk::Vector toItk(const vnl_vector_fixed& vnlVectorFixed) { return toItk(vnlVectorFixed.as_vector()); } template< class T, unsigned int NVectorDimension> itk::Vector toItk(const vnl_vector& vnlVector) { itk::Vector vector; vector.SetVnlVector(vnlVector); return vector; } static void Test_Vnl2Mitk_VectorFixedCompatibility() { Setup(); mitk::Vector3D vector3D = originalValues; vnl_vector_fixed vnlVectorFixed(valuesToCopy); vector3D = toItk(vnlVectorFixed); MITK_TEST_CONDITION( vector3D.GetVnlVector() == vnlVectorFixed, "vnl_vector_fixed assigned to mitk vector") MITK_TEST_CONDITION( vector3D == valuesToCopy, "correct values were assigned" ) } static void Test_Vnl2Mitk_VectorCompatibility() { Setup(); mitk::Vector3D vector3D = originalValues; vnl_vector vnlVector(3); vnlVector.set(valuesToCopy); vector3D = toItk(vnlVector); MITK_TEST_CONDITION( vector3D.GetVnlVector() == vnlVector, "vnl_vector assigned to mitk vector") MITK_TEST_CONDITION( vector3D == valuesToCopy, "correct values were assigned" ) } static void Test_Mitk2Vnl_PointCompatibility() { Setup(); //vnl_vector_fixed copiedPoint; // copiedPoint = mitk2vnl(point3D); //MITK_TEST_CONDITION( // Equal(static_cast(copiedPoint[0]), point3D[0]) // && Equal(static_cast(copiedPoint[1]), point3D[1]) // && Equal(static_cast(copiedPoint[2]), point3D[2]), "mitk point assigned to vnl point") } /** * Test the conversions from and to mitk types */ int mitkTypeConversionTest(int /*argc*/ , char* /*argv*/[]) { // always start with this! MITK_TEST_BEGIN("TypeConversionTest") Test_Mitk2Itk_PointCompatibility(); Test_Itk2Mitk_PointCompatibility(); Test_Vtk2Mitk_PointCompatibility(); Test_Mitk2Vtk_PointCompatibility(); Test_Vnl2Mitk_VectorFixedCompatibility(); Test_Vnl2Mitk_VectorCompatibility(); Test_Mitk2Vnl_PointCompatibility(); Test_Mitk2Pod_PointCompatibility(); Test_Pod2Mitk_PointCompatibility(); MITK_TEST_END() } diff --git a/Core/Code/Testing/mitkTypeOperationTest.cpp b/Core/Code/Testing/mitkTypeOperationTest.cpp index f28030d2f8..42f18844fd 100644 --- a/Core/Code/Testing/mitkTypeOperationTest.cpp +++ b/Core/Code/Testing/mitkTypeOperationTest.cpp @@ -1,50 +1,50 @@ /*=================================================================== 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 "mitkTestingMacros.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include using namespace mitk; Point3D a, b, c; static void Setup(void) { } static void TestAddition(void) { Setup(); // c = a + b; MITK_TEST_CONDITION_REQUIRED(false, "this test is passed if there is no compile error in this method when not commented out :)") } int mitkTypeOperationTest(int /*argc*/ , char* /*argv*/[]) { // always start with this! MITK_TEST_BEGIN("TypeOperationTest") TestAddition(); MITK_TEST_END() } diff --git a/Core/Code/Testing/mitkVectorTest.cpp b/Core/Code/Testing/mitkVectorTest.cpp index cfe371615a..22109e8049 100644 --- a/Core/Code/Testing/mitkVectorTest.cpp +++ b/Core/Code/Testing/mitkVectorTest.cpp @@ -1,137 +1,137 @@ /*=================================================================== 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 -#include +#include int mitkVectorTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN("mitkVector"); // test itk vector equality methods itk::Vector itkVector_1; itkVector_1[0] = 4.6; itkVector_1[1] = 9.76543; itkVector_1[2] = 746.09; itk::Vector itkVector_2; itk::Vector itkVector_3; for (int i=0; i<3; i++) { itkVector_2[i] = itkVector_1[i] - mitk::eps*1.1; itkVector_3[i] = itkVector_1[i] - mitk::eps*0.9; } MITK_TEST_CONDITION(mitk::Equal(itkVector_1,itkVector_1), "Test vector equality using the same vector with mitk::eps"); MITK_TEST_CONDITION(!mitk::Equal(itkVector_1,itkVector_2), "Test vector equality using different vectors with an element-wise difference greater than mitk::eps"); MITK_TEST_CONDITION( mitk::Equal(itkVector_1, itkVector_2, mitk::eps*1.2), "Vectors are equal for higher epsilon tolerance ( 1.2 * mitk::eps )"); MITK_TEST_CONDITION(mitk::Equal(itkVector_1,itkVector_3), "Test vector equality using different vectors with an element-wise difference less than mitk::eps"); // test itk point equality methods itk::Point itkPoint_1; itk::Point itkPoint_2; itk::Point itkPoint_3; for (int i=0; i<3; i++) { itkPoint_1[i] = itkVector_1[i]; itkPoint_2[i] = itkVector_2[i]; itkPoint_3[i] = itkVector_3[i]; } MITK_TEST_CONDITION(mitk::Equal(itkPoint_1,itkPoint_1), "Test point equality using the same point with mitk::eps"); MITK_TEST_CONDITION(!mitk::Equal(itkPoint_1,itkPoint_2), "Test point equality using different points with an element-wise difference greater than mitk::eps"); MITK_TEST_CONDITION( mitk::Equal(itkPoint_1, itkPoint_2, mitk::eps * 1.2), "Points are equal for higher epsilon tolerance ( 1.2 * mitk::eps )"); MITK_TEST_CONDITION(mitk::Equal(itkPoint_1,itkPoint_3), "Test point equality using different points with an element-wise difference less than mitk::eps"); // test mitk vnl vector equality methods mitk::VnlVector mitk_vnl_vector_1(3); mitk::VnlVector mitk_vnl_vector_2(3); mitk::VnlVector mitk_vnl_vector_3(3); for (int i=0; i<3; i++) { mitk_vnl_vector_1.put(i,itkVector_1[i]); mitk_vnl_vector_2.put(i,itkVector_2[i]); mitk_vnl_vector_3.put(i,itkVector_1[i]); } MITK_TEST_CONDITION(mitk::Equal(mitk_vnl_vector_1,mitk_vnl_vector_1), "Test mitk vnl vector equality using the same mitk vnl vector with mitk::eps"); MITK_TEST_CONDITION(!mitk::Equal(mitk_vnl_vector_1,mitk_vnl_vector_2), "Test mitk vnl vector equality using different mitk vnl vectors with an element-wise difference greater than mitk::eps"); MITK_TEST_CONDITION( mitk::Equal(mitk_vnl_vector_1, mitk_vnl_vector_2, mitk::eps*1.2), "Vnl vectors are equal for higher epsilon tolerance ( 1.2 * mitk::eps )"); MITK_TEST_CONDITION(mitk::Equal(mitk_vnl_vector_1,mitk_vnl_vector_3), "Test mitk vnl vector equality using different mitk vnl vectors with an element-wise difference less than mitk::eps"); // test vnl_vector equality method typedef mitk::ScalarType VnlValueType; vnl_vector_fixed vnlVector_1; vnlVector_1[3] = 56.98; vnlVector_1[4] = 22.32; vnlVector_1[5] = 1.00; vnlVector_1[6] = 746.09; vnl_vector_fixed vnlVector_2; vnl_vector_fixed vnlVector_3; for (int i=0; i<7; i++) { if (i<3) { vnlVector_1.put(i,itkVector_1[i]); } vnlVector_2[i] = vnlVector_1[i] - mitk::eps * 1.1f; vnlVector_3[i] = vnlVector_1[i] - mitk::eps * 0.9f; } MITK_TEST_CONDITION( (mitk::Equal(vnlVector_1,vnlVector_1)), "vnl_fixed : v_1 == v_1 "); // the v_2 is constructed so that the equality test fails for mitk::eps, the norm of the difference between the vectors is 7 * eps/6.9 MITK_TEST_CONDITION(!(mitk::Equal(vnlVector_1,vnlVector_2)), "vnl_fixed : v_1 != v_2 with mitk::eps "); // increase the epsilon value used for testing equality - should now pass ( 1.2 * mitk::eps > 7 * mitk::eps/6.9 ) MITK_TEST_CONDITION( (mitk::Equal(vnlVector_1,vnlVector_2, mitk::eps*1.2f)) , "vnl_fixed : v_1 == v_2 with eps = 1.2 * mitk::eps "); MITK_TEST_CONDITION( (mitk::Equal(vnlVector_1,vnlVector_3, mitk::eps)), "vnl_fixed : v_1 == v_3 with eps = 0.8 * mitk::eps "); MITK_TEST_CONDITION(!(mitk::Equal(vnlVector_1,vnlVector_3, mitk::eps*0.8f)), "vnl_fixed : v_1 != v_3 with eps = 0.8 * mitk::eps "); // test scalar equality method mitk::ScalarType scalar1 = 0.5689; mitk::ScalarType scalar2 = scalar1 + mitk::eps; mitk::ScalarType scalar3 = scalar1 + mitk::eps*0.95; MITK_TEST_CONDITION(mitk::Equal(scalar1,scalar1), "Test scalar equality using the same scalar with mitk::eps"); MITK_TEST_CONDITION(!mitk::Equal(scalar1,scalar2), "Test scalar equality using the different scalars with a difference greater than mitk::eps"); MITK_TEST_CONDITION(mitk::Equal(scalar1,scalar3), "Test scalar equality using the different scalars with a difference less than mitk::eps"); // test matrix equality methods vnl_matrix_fixed vnlMatrix3x3_1; vnlMatrix3x3_1(0,0) = 1.1; vnlMatrix3x3_1(0,1) = 0.4; vnlMatrix3x3_1(0,2) = 5.3; vnlMatrix3x3_1(1,0) = 2.7; vnlMatrix3x3_1(1,1) = 3578.56418; vnlMatrix3x3_1(1,2) = 123.56; vnlMatrix3x3_1(2,0) = 546.89; vnlMatrix3x3_1(2,1) = 0.0001; vnlMatrix3x3_1(2,2) = 1.0; vnl_matrix_fixed vnlMatrix3x3_2; vnlMatrix3x3_2(0,0) = 1.1000009; vnlMatrix3x3_2(0,1) = 0.4000009; vnlMatrix3x3_2(0,2) = 5.3000009; vnlMatrix3x3_2(1,0) = 2.7000009; vnlMatrix3x3_2(1,1) = 3578.5641809; vnlMatrix3x3_2(1,2) = 123.5600009; vnlMatrix3x3_2(2,0) = 546.8900009; vnlMatrix3x3_2(2,1) = 0.0001009; vnlMatrix3x3_2(2,2) = 1.0000009; mitk::ScalarType epsilon = 0.000001; MITK_TEST_CONDITION(mitk::MatrixEqualElementWise(vnlMatrix3x3_1,vnlMatrix3x3_1,0.0),"Test for matrix equality with given epsilon=0.0 and exactly the same matrix elements"); MITK_TEST_CONDITION(!mitk::MatrixEqualElementWise(vnlMatrix3x3_1,vnlMatrix3x3_2,0.0),"Test for matrix equality with given epsilon=0.0 and slightly different matrix elements"); MITK_TEST_CONDITION(mitk::MatrixEqualElementWise(vnlMatrix3x3_1,vnlMatrix3x3_2,epsilon),"Test for matrix equality with given epsilon and slightly different matrix elements"); MITK_TEST_CONDITION(!mitk::MatrixEqualRMS(vnlMatrix3x3_1,vnlMatrix3x3_2,0.0),"Test for matrix equality with given epsilon=0.0 and slightly different matrix elements"); MITK_TEST_CONDITION(mitk::MatrixEqualRMS(vnlMatrix3x3_1,vnlMatrix3x3_2,epsilon),"Test for matrix equality with given epsilon and slightly different matrix elements"); MITK_TEST_END(); } diff --git a/Modules/CameraCalibration/mitkCameraIntrinsics.h b/Modules/CameraCalibration/mitkCameraIntrinsics.h index 2b9cb96ee0..ddcbeddbcf 100644 --- a/Modules/CameraCalibration/mitkCameraIntrinsics.h +++ b/Modules/CameraCalibration/mitkCameraIntrinsics.h @@ -1,144 +1,144 @@ /*=================================================================== 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. ===================================================================*/ #ifndef mitkCameraIntrinsics_h #define mitkCameraIntrinsics_h #include -#include +#include #include #include #include #include #include "mitkXMLSerializable.h" #include int mitkCameraIntrinsicsTest(int argc, char* argv[]); namespace mitk { /// /// \brief class representing camera intrinsics and related functions /// class mitkCameraCalibration_EXPORT CameraIntrinsics: virtual public itk::Object, virtual public mitk::XMLSerializable { public: /// /// for testing purposes /// friend int mitkCameraIntrinsicsTest(int argc, char* argv[]); /// /// smartpointer typedefs /// mitkClassMacro(CameraIntrinsics, itk::Object); /// /// the static new function /// itkFactorylessNewMacro(Self); /// /// make a clone of this intrinsics /// itkCloneMacro(Self) /// /// copy information from other to this /// void Copy(const CameraIntrinsics* other); /// /// checks two intrinsics for equality /// bool Equals( const CameraIntrinsics* other ) const; /// /// \return the intrinsic parameter matrix as a 3x3 vnl matrix /// vnl_matrix_fixed GetVnlCameraMatrix() const; /// /// \return the intrinsic parameter matrix as a 3x4 vnl matrix /// (the last column only containing zeros) /// vnl_matrix_fixed GetVnlCameraMatrix3x4() const; /// /// \return true if the intrinsics are set (some plausibility checks /// may be done here) /// bool IsValid() const; void SetValid(bool valid); cv::Mat GetCameraMatrix() const; cv::Mat GetDistorsionCoeffs(); cv::Mat GetDistorsionCoeffs() const; void ToXML(TiXmlElement* elem) const; std::string ToString() const; std::string GetString(); double GetFocalLengthX() const; double GetFocalLengthY() const; double GetPrincipalPointX() const; double GetPrincipalPointY() const; mitk::Point4D GetDistorsionCoeffsAsPoint4D() const; mitk::Point3D GetFocalPoint() const; mitk::Point3D GetPrincipalPoint() const; vnl_vector_fixed GetFocalPointAsVnlVector() const; vnl_vector_fixed GetPrincipalPointAsVnlVector() const; /// /// set a new camera matrix utilizing a vnl matrix /// void SetCameraMatrix( const vnl_matrix_fixed& _CameraMatrix ); void SetIntrinsics( const cv::Mat& _CameraMatrix , const cv::Mat& _DistorsionCoeffs); void SetFocalLength( double x, double y ); void SetPrincipalPoint( double x, double y ); void SetDistorsionCoeffs( double k1, double k2, double p1, double p2 ); void SetIntrinsics( const mitk::Point3D& focalPoint, const mitk::Point3D& principalPoint, const mitk::Point4D& distortionCoefficients); void FromXML(TiXmlElement* elem); void FromGMLCalibrationXML(TiXmlElement* elem); std::string ToOctaveString(const std::string& varName="CameraIntrinsics"); virtual ~CameraIntrinsics(); protected: CameraIntrinsics(); CameraIntrinsics(const CameraIntrinsics& other); cv::Mat m_CameraMatrix; cv::Mat m_DistorsionCoeffs; bool m_Valid; itk::FastMutexLock::Pointer m_Mutex; private: virtual itk::LightObject::Pointer InternalClone() const; }; } // namespace mitk mitkCameraCalibration_EXPORT std::ostream& operator<< (std::ostream& os, mitk::CameraIntrinsics::Pointer p); #endif // mitkCameraIntrinsics_h diff --git a/Modules/CameraCalibration/mitkTransform.h b/Modules/CameraCalibration/mitkTransform.h index ca03343940..483d494348 100644 --- a/Modules/CameraCalibration/mitkTransform.h +++ b/Modules/CameraCalibration/mitkTransform.h @@ -1,305 +1,305 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKTRANSFORM_H #define MITKTRANSFORM_H #include #include #include -#include +#include #include #include #include #include #include #include namespace mitk { /// /// \brief class representing a transfrom in 3D /// /// internally it stores a mitk navigation data. this is more /// or less a wrapper for navigation data for easy casting /// between opencv/vnl/mitk/xml representations of transform /// data /// class mitkCameraCalibration_EXPORT Transform: public itk::Object, public XMLSerializable { public: mitkClassMacro(Transform, itk::Object); itkFactorylessNewMacro(Transform); mitkNewMacro1Param(Transform, const mitk::NavigationData*); mitkNewMacro1Param(Transform, const std::string&); /// /// constants describing the type of transform /// represented here /// static const std::string UNKNOWN_TYPE; static const std::string ENDOSCOPE_SCOPE_TOOL; static const std::string ENDOSCOPE_CAM_TOOL; static const std::string CHESSBOARD_TOOL; static const std::string POINTER_TOOL; static const std::string POINTER_TO_CHESSBOARD_ORIGIN; static const std::string POINTER_TO_CHESSBOARD_X_SUPPORT_POINT; static const std::string POINTER_TO_CHESSBOARD_Y_SUPPORT_POINT; static const std::string BOARD_TO_BOARD_TOOL; static const std::string REFERENCE_CAMERA_TRANSFORM; static const std::string REFERENCE_SCOPE_TRANSFORM; static const std::string EYE_TO_HAND_TRANSFORM; static const std::string CAMERA_EXTRINSICS; itkGetConstMacro(Type, std::string); itkSetMacro(Type, std::string&); /// /// Copies the content of transform to this /// instance /// void Copy( const mitk::Transform* transform ); /// /// Copies the content of transform to this /// instance /// void Copy( const mitk::NavigationData* transform ); /// /// Inverts the rotation of this transform /// (Polaris navigation Data have inverted rotation /// so you may want to call this function when using /// polaris data) /// void TransposeRotation(); /// /// get a copy of this transform /// mitk::Transform::Pointer Clone() const; /// /// concatenate this transform with the given one, /// i.e. this transform is done first, then transform /// ( if x is this transform, y is transform, then this will be y*x) /// post multiply semantics! /// \see vtkTransform /// void Concatenate( mitk::Transform* transform ); /// /// same as above with vnl mat argument /// void Concatenate( const vnl_matrix_fixed& transform ); /// /// same as above with vtk mat argument /// void Concatenate( const vtkMatrix4x4* transform ); /// /// invert this transform /// void Invert(); /// /// resets the internal variables except type /// void Reset(); /// /// read from xml /// void FromXML(TiXmlElement* elem); /// /// read csv file /// void FromCSVFile(const std::string& file); /// /// grafts the data from naviData to this transform /// void SetNavigationData( const mitk::NavigationData* naviData ); /// /// method to set orientation quat /// void SetOrientation( const vnl_quaternion& orientation); /// /// method to set float valued orientation quat /// void SetOrientation( const vnl_quaternion& orientation); /// /// method to set translation /// void SetTranslation( const vnl_vector_fixed& transl); /// /// method to set a vector of doubles as translation /// void SetTranslation( const vnl_vector& transl); /// /// method to set a mitk::Point3D as position /// void SetPosition( const mitk::Point3D& transl); /// /// sets rotation with a rotation matrix /// void SetRotation( vnl_matrix_fixed& mat); /// /// sets rotation with a non fixed rotation matrix /// void SetRotation( vnl_matrix& mat); /// /// sets rotation and translation with a transformation matrix /// void SetMatrix( const vnl_matrix_fixed& mat); /// /// sets rotation and translation with a vtk transformation matrix /// void SetMatrix( const vtkMatrix4x4* mat); /// /// sets translation from a POD vector /// void SetTranslation( float* array ); /// /// sets translation from a POD vector. this must be a /// 3x3=9 sized vector in row major format (first row = first /// three elements) /// void SetRotation( float* array ); /// /// sets translation from a POD vector /// void SetTranslation( double array[3] ); /// /// sets translation from a POD vector /// void SetRotation( double array[3][3] ); /// /// method to set translation by cv vector /// void SetTranslation( const cv::Mat& transl); /// /// sets rotation with a rotation matrix /// void SetRotation( const cv::Mat& mat ); /// /// sets rotation with a rodrigues rotation vector /// void SetRotationVector( const cv::Mat& rotVec); /// /// \return the navigation data that stores all information /// mitk::NavigationData::Pointer GetNavigationData() const; /// /// calls navigationdata::GetPosition() /// mitk::Point3D GetPosition() const; /// /// same as GetPosition /// mitk::Point3D GetTranslation() const; /// /// calls navigationdata::IsValid() /// bool IsValid() const; /// /// calls navigationdata::SetValid() /// void SetValid(bool valid); /// /// calls navigationdata::GetOrientation() /// mitk::Quaternion GetOrientation() const; /// /// \return the homogeneous matrix representing this transform /// vnl_matrix_fixed GetMatrix() const; /// /// \return the homogeneous vtk matrix representing this transform /// void GetMatrix(vtkMatrix4x4* matrix) const; /// /// \return the homogeneous vtk matrix representing this transform /// in !OpenGL! left handed coordinate system /// void GetVtkOpenGlMatrix(vtkMatrix4x4* matrix) const; mitk::Point3D TransformPoint(mitk::Point3D point) const; /// /// create xml representation /// void ToXML(TiXmlElement* elem) const; /// /// create string representation /// std::string ToString() const; /// /// create string csv representation (only the transformation values!!!!) /// std::string ToCSVString() const; /// /// create matlab representation /// std::string ToMatlabString(const std::string& varname="transform", bool printLastRow=true) const; /// /// write csv representation to file (only the transformation values!!!!) /// void ToCSVFile(const std::string& file) const; /// /// write matlab representation to file /// void ToMatlabFile(const std::string& file , const std::string& varname="transform") const; /// /// conversion to cv types /// cv::Mat GetCvTranslation() const; cv::Mat GetCvRotationVector() const; cv::Mat GetCvRotationMatrix() const; cv::Mat GetCvMatrix() const; /// /// conversion to vnl types /// vnl_vector_fixed GetVnlTranslation() const; vnl_vector_fixed GetVnlDoubleTranslation() const; vnl_quaternion GetVnlDoubleQuaternion() const; vnl_matrix_fixed GetVnlRotationMatrix() const; vnl_matrix_fixed GetVnlDoubleMatrix() const; protected: Transform(); Transform(const mitk::NavigationData* nd); Transform(const std::string& s); // everything is stored here mitk::NavigationData::Pointer m_NavData; /// /// saves the type of the transform (Default is UNKNOWN_TYPE) /// std::string m_Type; }; } // namespace mitk mitkCameraCalibration_EXPORT std::ostream& operator<< (std::ostream& os, mitk::Transform::Pointer p); #endif // MITKTRANSFORM_H diff --git a/Modules/ClippingTools/mitkClippingPlaneDeformationTool.h b/Modules/ClippingTools/mitkClippingPlaneDeformationTool.h index 9419815855..d7acf7ebb2 100644 --- a/Modules/ClippingTools/mitkClippingPlaneDeformationTool.h +++ b/Modules/ClippingTools/mitkClippingPlaneDeformationTool.h @@ -1,65 +1,65 @@ /*=================================================================== 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. ===================================================================*/ #ifndef mitkClippingPlaneDeformationTool_h_Included #define mitkClippingPlaneDeformationTool_h_Included #include "ClippingToolsExports.h" #include "mitkCommon.h" #include "mitkDataNode.h" #include "mitkSurfaceDeformationInteractor3D.h" #include "mitkTool.h" -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { /** \brief A tool with whom you can deform planes. */ class ClippingTools_EXPORT ClippingPlaneDeformationTool : public Tool { public: mitkClassMacro(ClippingPlaneDeformationTool, Tool); itkNewMacro(ClippingPlaneDeformationTool); virtual const char** GetXPM() const; virtual const char* GetName() const; virtual const char* GetGroup() const; protected: ClippingPlaneDeformationTool(); // purposely hidden virtual ~ClippingPlaneDeformationTool(); virtual void Activated(); virtual void Deactivated(); mitk::DataNode::Pointer m_ClippingPlaneNode; mitk::SurfaceDeformationInteractor3D::Pointer m_SurfaceInteractor; private: void ClippingPlaneChanged(); }; } //end namespace mitk #endif diff --git a/Modules/ClippingTools/mitkClippingPlaneRotationTool.h b/Modules/ClippingTools/mitkClippingPlaneRotationTool.h index 1cd152513c..66d3c6930d 100644 --- a/Modules/ClippingTools/mitkClippingPlaneRotationTool.h +++ b/Modules/ClippingTools/mitkClippingPlaneRotationTool.h @@ -1,66 +1,66 @@ /*=================================================================== 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. ===================================================================*/ #ifndef mitkClippingPlaneRotationTool_h_Included #define mitkClippingPlaneRotationTool_h_Included #include "ClippingToolsExports.h" #include "mitkAffineInteractor3D.h" #include "mitkCommon.h" #include "mitkDataNode.h" #include "mitkTool.h" -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { /** \brief A tool which allows you to rotate planes. */ class ClippingTools_EXPORT ClippingPlaneRotationTool : public Tool { public: mitkClassMacro(ClippingPlaneRotationTool, Tool); itkNewMacro(ClippingPlaneRotationTool); virtual const char** GetXPM() const; virtual const char* GetName() const; virtual const char* GetGroup() const; protected: ClippingPlaneRotationTool(); // purposely hidden virtual ~ClippingPlaneRotationTool(); virtual void Activated(); virtual void Deactivated(); mitk::DataNode::Pointer m_ClippingPlaneNode; mitk::AffineInteractor3D::Pointer m_AffineInteractor; private: void ClippingPlaneChanged(); }; } //end namespace mitk #endif diff --git a/Modules/ClippingTools/mitkClippingPlaneTranslationTool.h b/Modules/ClippingTools/mitkClippingPlaneTranslationTool.h index 228dd88a29..07068c150a 100644 --- a/Modules/ClippingTools/mitkClippingPlaneTranslationTool.h +++ b/Modules/ClippingTools/mitkClippingPlaneTranslationTool.h @@ -1,66 +1,66 @@ /*=================================================================== 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. ===================================================================*/ #ifndef mitkClippingPlaneTranslationTool_h_Included #define mitkClippingPlaneTranslationTool_h_Included #include "ClippingToolsExports.h" #include "mitkAffineInteractor3D.h" #include "mitkCommon.h" #include "mitkDataNode.h" #include "mitkTool.h" -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { /** \brief A tool which allows you to move planes. */ class ClippingTools_EXPORT ClippingPlaneTranslationTool : public Tool { public: mitkClassMacro(ClippingPlaneTranslationTool, Tool); itkNewMacro(ClippingPlaneTranslationTool); virtual const char** GetXPM() const; virtual const char* GetName() const; virtual const char* GetGroup() const; protected: ClippingPlaneTranslationTool(); // purposely hidden virtual ~ClippingPlaneTranslationTool(); virtual void Activated(); virtual void Deactivated(); mitk::DataNode::Pointer m_ClippingPlaneNode; mitk::AffineInteractor3D::Pointer m_AffineInteractor; private: void ClippingPlaneChanged(); }; } //end namespace mitk #endif diff --git a/Modules/DiffusionImaging/DiffusionCore/mitkDiffusionFunctionCollection.cpp b/Modules/DiffusionImaging/DiffusionCore/mitkDiffusionFunctionCollection.cpp index e7fe6c5b5c..759c0858f5 100644 --- a/Modules/DiffusionImaging/DiffusionCore/mitkDiffusionFunctionCollection.cpp +++ b/Modules/DiffusionImaging/DiffusionCore/mitkDiffusionFunctionCollection.cpp @@ -1,250 +1,250 @@ /*=================================================================== 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 "mitkDiffusionFunctionCollection.h" #include -#include "mitkVector.h" +#include "mitkTypes.h" // for Windows #ifndef M_PI #define M_PI 3.14159265358979323846 #endif // Namespace ::SH #include #include #include // Namespace ::Gradients #include "itkVectorContainer.h" #include "vnl/vnl_vector.h" //------------------------- SH-function ------------------------------------ double mitk::sh::factorial(int number) { if(number <= 1) return 1; double result = 1.0; for(int i=1; i<=number; i++) result *= i; return result; } void mitk::sh::Cart2Sph(double x, double y, double z, double *cart) { double phi, th, rad; rad = sqrt(x*x+y*y+z*z); if( rad < mitk::eps ) { th = M_PI/2; phi = M_PI/2; } else { th = acos(z/rad); phi = atan2(y, x); } cart[0] = phi; cart[1] = th; cart[2] = rad; } double mitk::sh::legendre0(int l) { if( l%2 != 0 ) { return 0; } else { double prod1 = 1.0; for(int i=1;i mitk::gradients::GetAllUniqueDirections(const BValueMap & refBValueMap, GradientDirectionContainerType *refGradientsContainer ) { IndiciesVector directioncontainer; BValueMap::const_iterator mapIterator = refBValueMap.begin(); if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1) mapIterator++; //skip bzero Values for( ; mapIterator != refBValueMap.end(); mapIterator++){ IndiciesVector currentShell = mapIterator->second; while(currentShell.size()>0) { unsigned int wntIndex = currentShell.back(); currentShell.pop_back(); IndiciesVector::iterator containerIt = directioncontainer.begin(); bool directionExist = false; while(containerIt != directioncontainer.end()) { if (fabs(dot(refGradientsContainer->ElementAt(*containerIt), refGradientsContainer->ElementAt(wntIndex))) > 0.9998) { directionExist = true; break; } containerIt++; } if(!directionExist) { directioncontainer.push_back(wntIndex); } } } return directioncontainer; } bool mitk::gradients::CheckForDifferingShellDirections(const BValueMap & refBValueMap, GradientDirectionContainerType::ConstPointer refGradientsContainer) { BValueMap::const_iterator mapIterator = refBValueMap.begin(); if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1) mapIterator++; //skip bzero Values for( ; mapIterator != refBValueMap.end(); mapIterator++){ BValueMap::const_iterator mapIterator_2 = refBValueMap.begin(); if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1) mapIterator_2++; //skip bzero Values for( ; mapIterator_2 != refBValueMap.end(); mapIterator_2++){ if(mapIterator_2 == mapIterator) continue; IndiciesVector currentShell = mapIterator->second; IndiciesVector testShell = mapIterator_2->second; for (unsigned int i = 0; i< currentShell.size(); i++) if (fabs(dot(refGradientsContainer->ElementAt(currentShell[i]), refGradientsContainer->ElementAt(testShell[i]))) <= 0.9998) { return true; } } } return false; } template double mitk::gradients::dot (vnl_vector_fixed< type ,3> const& v1, vnl_vector_fixed< type ,3 > const& v2 ) { double result = (v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]) / (v1.two_norm() * v2.two_norm()); return result ; } vnl_matrix mitk::gradients::ComputeSphericalFromCartesian(const IndiciesVector & refShell, const GradientDirectionContainerType * refGradientsContainer) { vnl_matrix Q(3, refShell.size()); for(unsigned int i = 0; i < refShell.size(); i++) { GradientDirectionType dir = refGradientsContainer->ElementAt(refShell[i]); double x = dir.normalize().get(0); double y = dir.normalize().get(1); double z = dir.normalize().get(2); double cart[3]; mitk::sh::Cart2Sph(x,y,z,cart); Q(0,i) = cart[0]; Q(1,i) = cart[1]; Q(2,i) = cart[2]; } return Q; } vnl_matrix mitk::gradients::ComputeSphericalHarmonicsBasis(const vnl_matrix & QBallReference, const unsigned int & LOrder) { vnl_matrix SHBasisOutput(QBallReference.cols(), (LOrder+1)*(LOrder+2)*0.5); for(unsigned int i=0; i< SHBasisOutput.rows(); i++) for(int k = 0; k <= LOrder; k += 2) for(int m =- k; m <= k; m++) { int j = ( k * k + k + 2 ) / 2 + m - 1; double phi = QBallReference(0,i); double th = QBallReference(1,i); SHBasisOutput(i,j) = mitk::sh::Yj(m,k,th,phi); } return SHBasisOutput; } mitk::gradients::GradientDirectionContainerType::Pointer mitk::gradients::CreateNormalizedUniqueGradientDirectionContainer(const mitk::gradients::BValueMap & bValueMap, const GradientDirectionContainerType *origninalGradentcontainer) { mitk::gradients::GradientDirectionContainerType::Pointer directioncontainer = mitk::gradients::GradientDirectionContainerType::New(); BValueMap::const_iterator mapIterator = bValueMap.begin(); if(bValueMap.find(0) != bValueMap.end() && bValueMap.size() > 1){ mapIterator++; //skip bzero Values vnl_vector_fixed vec; vec.fill(0.0); directioncontainer->push_back(vec); } for( ; mapIterator != bValueMap.end(); mapIterator++){ IndiciesVector currentShell = mapIterator->second; while(currentShell.size()>0) { unsigned int wntIndex = currentShell.back(); currentShell.pop_back(); mitk::gradients::GradientDirectionContainerType::Iterator containerIt = directioncontainer->Begin(); bool directionExist = false; while(containerIt != directioncontainer->End()) { if (fabs(dot(containerIt.Value(), origninalGradentcontainer->ElementAt(wntIndex))) > 0.9998) { directionExist = true; break; } containerIt++; } if(!directionExist) { GradientDirectionType dir(origninalGradentcontainer->ElementAt(wntIndex)); directioncontainer->push_back(dir.normalize()); } } } return directioncontainer; } diff --git a/Modules/DiffusionImaging/FiberTracking/Algorithms/itkFieldmapGeneratorFilter.h b/Modules/DiffusionImaging/FiberTracking/Algorithms/itkFieldmapGeneratorFilter.h index 73030eef3c..e03683eb88 100644 --- a/Modules/DiffusionImaging/FiberTracking/Algorithms/itkFieldmapGeneratorFilter.h +++ b/Modules/DiffusionImaging/FiberTracking/Algorithms/itkFieldmapGeneratorFilter.h @@ -1,85 +1,85 @@ /*=================================================================== 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. ===================================================================*/ #ifndef __itkFieldmapGeneratorFilter_h__ #define __itkFieldmapGeneratorFilter_h__ #include #include #include #include -#include +#include #include #include namespace itk{ /** * \brief Generates tract density images from input fiberbundles (Calamante 2010). */ template< class OutputImageType > class FieldmapGeneratorFilter : public ImageSource< OutputImageType > { public: typedef FieldmapGeneratorFilter Self; typedef ProcessObject Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; typedef typename OutputImageType::PixelType PixelType; typedef typename OutputImageType::IndexType IndexType; typedef itk::ImageRegion<3> OutputImageRegionType; typedef itk::Matrix MatrixType; itkNewMacro(Self) itkTypeMacro( FieldmapGeneratorFilter, ImageSource ) itkSetMacro( Spacing, itk::Vector ) itkSetMacro( Origin, mitk::Point3D ) itkSetMacro( DirectionMatrix, MatrixType ) itkSetMacro( ImageRegion, OutputImageRegionType ) void SetGradient( vnl_vector_fixed< double, 3 > gradient ) { m_Gradient=gradient; } void SetOffset( vnl_vector_fixed< double, 3 > offset ) { m_Offset=offset; } void SetVariances( std::vector< double > variances ) { m_Variances=variances; } void SetHeights( std::vector< double > heights ) { m_Heights=heights; } void SetWorldPositions( std::vector< mitk::Point3D > worldPositions ) { m_WorldPositions=worldPositions; } protected: void BeforeThreadedGenerateData(); void ThreadedGenerateData( const OutputImageRegionType &outputRegionForThread, ThreadIdType threadId); FieldmapGeneratorFilter(); virtual ~FieldmapGeneratorFilter(); itk::Vector m_Spacing; ///< output image spacing mitk::Point3D m_Origin; ///< output image origin MatrixType m_DirectionMatrix; ///< output image rotation OutputImageRegionType m_ImageRegion; ///< output image size std::vector< double > m_Variances; std::vector< double > m_Heights; std::vector< mitk::Point3D > m_WorldPositions; vnl_vector_fixed< double, 3 > m_Gradient; vnl_vector_fixed< double, 3 > m_Offset; }; } #ifndef ITK_MANUAL_INSTANTIATION #include "itkFieldmapGeneratorFilter.cpp" #endif #endif // __itkFieldmapGeneratorFilter_h__ diff --git a/Modules/DiffusionImaging/FiberTracking/Interactions/mitkFiberBundleInteractor.h b/Modules/DiffusionImaging/FiberTracking/Interactions/mitkFiberBundleInteractor.h index 8fdee475c2..fd17c51bb7 100644 --- a/Modules/DiffusionImaging/FiberTracking/Interactions/mitkFiberBundleInteractor.h +++ b/Modules/DiffusionImaging/FiberTracking/Interactions/mitkFiberBundleInteractor.h @@ -1,99 +1,99 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKFiberBundleINTERACTOR_H_HEADER_INCLUDED #define MITKFiberBundleINTERACTOR_H_HEADER_INCLUDED #include "mitkCommon.h" #include "MitkExtExports.h" #include -#include +#include #include "FiberTrackingExports.h" #include namespace mitk { class DataNode; //##Documentation //## @brief Just select a point, that's the only way to interact with the point //## //## Interact with a point: Select the point without moving to get parameters that does not change //## All Set-operations would be done through the method "ExecuteAction", if there would be anyone. //## the identificationnumber of this point is set by this points and evalued from an empty place in the DataStructure //## @ingroup Interaction class FiberTracking_EXPORT FiberBundleInteractor : public Interactor { public: mitkClassMacro(FiberBundleInteractor, Interactor); mitkNewMacro2Param(Self, const char*, DataNode*); //##Documentation //## @brief Sets the amount of precision void SetPrecision(unsigned int precision); //##Documentation //## @brief derived from mitk::Interactor; calculates Jurisdiction according to points //## //## standard method can not be used, since it doesn't calculate in points, only in BoundingBox of Points virtual float CanHandleEvent(StateEvent const* stateEvent) const; protected: //##Documentation //##@brief Constructor FiberBundleInteractor(const char * type, DataNode* dataNode); //##Documentation //##@brief Destructor virtual ~FiberBundleInteractor(); //##Documentation //## @brief select the point on the given position virtual void SelectFiber(int position); //##Documentation //## @brief unselect all points that exist in mesh virtual void DeselectAllFibers(); //##Documentation //## @brief Executes Actions virtual bool ExecuteAction(Action* action, mitk::StateEvent const* stateEvent); private: //##Documentation //## @brief to calculate a direction vector from last point and actual point Point3D m_LastPoint; //##Documentation //## @brief to store a position unsigned int m_LastPosition; // Point3D m_InitialPickedPoint; // Point2D m_InitialPickedDisplayPoint; // vtkFloatingPointType m_InitialPickedPointWorld[4]; Point3D m_CurrentPickedPoint; Point2D m_CurrentPickedDisplayPoint; vtkFloatingPointType m_CurrentPickedPointWorld[4]; }; } #endif /* MITKFiberBundleInteractor_H_HEADER_INCLUDED */ diff --git a/Modules/IGT/IGTFilters/mitkNavigationData.h b/Modules/IGT/IGTFilters/mitkNavigationData.h index 3a8cc9c7af..5860366e17 100644 --- a/Modules/IGT/IGTFilters/mitkNavigationData.h +++ b/Modules/IGT/IGTFilters/mitkNavigationData.h @@ -1,206 +1,206 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKNAVIGATIONDATA_H_HEADER_INCLUDED_ #define MITKNAVIGATIONDATA_H_HEADER_INCLUDED_ #include #include #include -#include +#include namespace mitk { /**Documentation * \brief Navigation Data * * This class represents the data object that is passed through the MITK-IGT navigation filter * pipeline. It encapsulates position and orientation of a tracked tool/sensor. Additionally, * it contains a data structure that contains error/plausibility information * * \ingroup IGT */ class MitkIGT_EXPORT NavigationData : public itk::DataObject { public: mitkClassMacro(NavigationData, itk::DataObject); itkNewMacro(Self); /** * \brief Type that holds the position part of the tracking data */ typedef mitk::Point3D PositionType; /** * \brief Type that holds the orientation part of the tracking data */ typedef mitk::Quaternion OrientationType; /** * \brief type that holds the error characterization of the position and orientation measurements */ typedef itk::Matrix CovarianceMatrixType; /** * \brief type that holds the time at which the data was recorded */ typedef double TimeStampType; /** * \brief sets the position of the NavigationData object */ itkSetMacro(Position, PositionType); /** * \brief returns position of the NavigationData object */ itkGetConstMacro(Position, PositionType); /** * \brief sets the orientation of the NavigationData object */ itkSetMacro(Orientation, OrientationType); /** * \brief returns the orientation of the NavigationData object */ itkGetConstMacro(Orientation, OrientationType); /** * \brief returns true if the object contains valid data */ virtual bool IsDataValid() const; /** * \brief sets the dataValid flag of the NavigationData object indicating if the object contains valid data */ itkSetMacro(DataValid, bool); /** * \brief sets the IGT timestamp of the NavigationData object */ itkSetMacro(IGTTimeStamp, TimeStampType); /** * \brief gets the IGT timestamp of the NavigationData object */ itkGetConstMacro(IGTTimeStamp, TimeStampType); /** * \brief sets the HasPosition flag of the NavigationData object */ itkSetMacro(HasPosition, bool); /** * \brief gets the HasPosition flag of the NavigationData object */ itkGetConstMacro(HasPosition, bool); /** * \brief sets the HasOrientation flag of the NavigationData object */ itkSetMacro(HasOrientation, bool); /** * \brief gets the HasOrientation flag of the NavigationData object */ itkGetConstMacro(HasOrientation, bool); /** * \brief sets the 6x6 Error Covariance Matrix of the NavigationData object */ itkSetMacro(CovErrorMatrix, CovarianceMatrixType); /** * \brief gets the 6x6 Error Covariance Matrix of the NavigationData object */ itkGetConstMacro(CovErrorMatrix, CovarianceMatrixType); /** * \brief set the name of the NavigationData object */ itkSetStringMacro(Name); /** * \brief returns the name of the NavigationData object */ itkGetStringMacro(Name); /** * \brief Graft the data and information from one NavigationData to another. * * Copies the content of data into this object. * This is a convenience method to setup a second NavigationData object with all the meta * information of another NavigationData object. * Note that this method is different than just using two * SmartPointers to the same NavigationData object since separate DataObjects are * still maintained. */ virtual void Graft(const DataObject *data); /** * \brief copy meta data of a NavigationData object * * copies all meta data from NavigationData data to this object */ virtual void CopyInformation(const DataObject* data); /** * \brief Prints the object information to the given stream os. * \param os The stream which is used to print the output. * \param indent Defines the indentation of the output. */ void PrintSelf(std::ostream& os, itk::Indent indent) const; /** * Set the position part of m_CovErrorMatrix to I*error^2 * This means that all position variables are assumed to be independent */ void SetPositionAccuracy(mitk::ScalarType error); /** * Set the orientation part of m_CovErrorMatrix to I*error^2 * This means that all orientation variables are assumed to be independent */ void SetOrientationAccuracy(mitk::ScalarType error); protected: NavigationData(); virtual ~NavigationData(); /** * \brief holds the position part of the tracking data */ PositionType m_Position; /** * \brief holds the orientation part of the tracking data */ OrientationType m_Orientation; /** * \brief A 6x6 covariance matrix parameterizing the Gaussian error * distribution of the measured position and orientation. * * The hasPosition/hasOrientation fields define which entries * are valid. */ CovarianceMatrixType m_CovErrorMatrix; ///< holds the error characterization of the position and orientation /** * \brief defines if position part of m_CovErrorMatrix is valid */ bool m_HasPosition; /** * \brief defines if orientation part of m_CovErrorMatrix is valid */ bool m_HasOrientation; /** * \brief defines if the object contains valid values */ bool m_DataValid; /** * \brief contains the time at which the tracking data was recorded */ TimeStampType m_IGTTimeStamp; /** * \brief name of the navigation data */ std::string m_Name; }; } // namespace mitk #endif /* MITKNAVIGATIONDATA_H_HEADER_INCLUDED_ */ diff --git a/Modules/IGT/IGTTrackingDevices/mitkClaronInterface.cpp b/Modules/IGT/IGTTrackingDevices/mitkClaronInterface.cpp index 38ba997c30..5712c815db 100644 --- a/Modules/IGT/IGTTrackingDevices/mitkClaronInterface.cpp +++ b/Modules/IGT/IGTTrackingDevices/mitkClaronInterface.cpp @@ -1,291 +1,291 @@ /*=================================================================== 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 #include #include #include -#include +#include mitk::ClaronInterface::ClaronInterface() { isTracking = false; sprintf(calibrationDir,"No calibration dir set yet"); sprintf(markerDir,"No marker dir set yet"); } mitk::ClaronInterface::~ClaronInterface() { } void mitk::ClaronInterface::Initialize(std::string calibrationDir, std::string toolFilesDir) { sprintf(this->calibrationDir, calibrationDir.c_str()); sprintf(this->markerDir,toolFilesDir.c_str()); this->IdentifiedMarkers = 0; this->PoseXf = 0; this->CurrCamera = 0; this->IdentifyingCamera = 0; } bool mitk::ClaronInterface::StartTracking() { isTracking = false; MTC( Cameras_AttachAvailableCameras(calibrationDir) ); //Connect to camera if (Cameras_Count() < 1) { printf("No camera found!\n"); return false; } try { //Step 1: initialize cameras MTC(Cameras_HistogramEqualizeImagesSet(true)); //set the histogram equalizing MTC( Cameras_ItemGet(0, &CurrCamera) ); //Obtain a handle to the first/only camera in the array MITK_INFO< mitk::ClaronInterface::GetAllActiveTools() { //Set returnvalue std::vector returnValue; //Here, MTC internally maintains the measurement results. //Those results can be accessed until the next call to Markers_ProcessFrame, when they //are updated to reflect the next frame's content. //First, we will obtain the collection of the markers that were identified. MTC( Markers_IdentifiedMarkersGet(NULL, IdentifiedMarkers) ); //Now we iterate on the identified markers and add them to the returnvalue for (int j=1; j<=Collection_Count(IdentifiedMarkers); j++) { // Obtain the marker's handle, and use it to obtain the pose in the current camera's space // using our Xform3D object, PoseXf. mtHandle Marker = Collection_Int(IdentifiedMarkers, j); returnValue.push_back(Marker); } return returnValue; } void mitk::ClaronInterface::GrabFrame() { MTC( Cameras_GrabFrame(NULL) ); //Grab a frame MTC( Markers_ProcessFrame(NULL) ); //Process the frame(s) } std::vector mitk::ClaronInterface::GetTipPosition(mitk::claronToolHandle c) { std::vector returnValue; double Position[3]; mtHandle t2m = Xform3D_New(); // tooltip to marker xform handle mtHandle t2c = Xform3D_New(); // tooltip to camera xform handle mtHandle m2c = Xform3D_New(); // marker to camera xform handle //Get m2c MTC( Marker_Marker2CameraXfGet (c, CurrCamera, m2c, &IdentifyingCamera) ); //Get t2m MTC( Marker_Tooltip2MarkerXfGet (c, t2m )); //Transform both to t2c MTC(Xform3D_Concatenate(t2m,m2c,t2c)); //Get position MTC( Xform3D_ShiftGet(t2c, Position) ); // Here we have to negate the X- and Y-coordinates because of a bug of the // MTC-library. returnValue.push_back(-Position[0]); returnValue.push_back(-Position[1]); returnValue.push_back(Position[2]); return returnValue; } std::vector mitk::ClaronInterface::GetPosition(claronToolHandle c) { std::vector returnValue; double Position[3]; MTC( Marker_Marker2CameraXfGet (c, CurrCamera, PoseXf, &IdentifyingCamera) ); MTC( Xform3D_ShiftGet(PoseXf, Position) ); // Here we have to negate the X- and Y-coordinates because of a bug of the // MTC-library. returnValue.push_back(-Position[0]); returnValue.push_back(-Position[1]); returnValue.push_back(Position[2]); return returnValue; } std::vector mitk::ClaronInterface::GetTipQuaternions(claronToolHandle c) { std::vector returnValue; mtHandle t2m = Xform3D_New(); // tooltip to marker xform handle mtHandle t2c = Xform3D_New(); // tooltip to camera xform handle mtHandle m2c = Xform3D_New(); // marker to camera xform handle //Get m2c MTC( Marker_Marker2CameraXfGet (c, CurrCamera, m2c, &IdentifyingCamera) ); //Get t2m MTC( Marker_Tooltip2MarkerXfGet (c, t2m )); //Transform both to t2c MTC(Xform3D_Concatenate(t2m,m2c,t2c)); //get the Claron-Quaternion double Quarternions[4]; MTC( Xform3D_RotQuaternionsGet(t2c, Quarternions) ); mitk::Quaternion claronQuaternion; //note: claron quarternion has different order than the mitk quarternion claronQuaternion[3] = Quarternions[0]; claronQuaternion[0] = Quarternions[1]; claronQuaternion[1] = Quarternions[2]; claronQuaternion[2] = Quarternions[3]; - // Here we have to make a -90°-turn around the Y-axis because of a bug of the + // Here we have to make a -90�-turn around the Y-axis because of a bug of the // MTC-library. mitk::Quaternion minusNinetyDegreeY; minusNinetyDegreeY[3] = sqrt(2.0)/2.0; minusNinetyDegreeY[0] = 0; minusNinetyDegreeY[1] = -1.0/(sqrt(2.0)); minusNinetyDegreeY[2] = 0; //calculate the result... mitk::Quaternion erg = (minusNinetyDegreeY*claronQuaternion); returnValue.push_back(erg[3]); returnValue.push_back(erg[0]); returnValue.push_back(erg[1]); returnValue.push_back(erg[2]); return returnValue; } std::vector mitk::ClaronInterface::GetQuaternions(claronToolHandle c) { std::vector returnValue; double Quarternions[4]; MTC( Marker_Marker2CameraXfGet (c, CurrCamera, PoseXf, &IdentifyingCamera) ); MTC( Xform3D_RotQuaternionsGet(PoseXf, Quarternions) ); //here we have to compensate a bug in the MTC-lib. (difficult to understand) mitk::Quaternion claronQuaternion; //note: claron quarternion has different order than the mitk quarternion claronQuaternion[3] = Quarternions[0]; claronQuaternion[0] = Quarternions[1]; claronQuaternion[1] = Quarternions[2]; claronQuaternion[2] = Quarternions[3]; - // Here we have to make a -90°-turn around the Y-axis because of a bug of the + // Here we have to make a -90�-turn around the Y-axis because of a bug of the // MTC-library. mitk::Quaternion minusNinetyDegreeY; minusNinetyDegreeY[3] = sqrt(2.0)/2.0; minusNinetyDegreeY[0] = 0; minusNinetyDegreeY[1] = -1.0/(sqrt(2.0)); minusNinetyDegreeY[2] = 0; //calculate the result... mitk::Quaternion erg = (minusNinetyDegreeY*claronQuaternion); returnValue.push_back(erg[3]); returnValue.push_back(erg[0]); returnValue.push_back(erg[1]); returnValue.push_back(erg[2]); return returnValue; } const char* mitk::ClaronInterface::GetName(claronToolHandle c) { char MarkerName[MT_MAX_STRING_LENGTH]; MTC( Marker_NameGet(c, MarkerName, MT_MAX_STRING_LENGTH, 0) ); std::string* returnValue = new std::string(MarkerName); return returnValue->c_str(); } bool mitk::ClaronInterface::IsTracking() { return this->isTracking; } bool mitk::ClaronInterface::IsMicronTrackerInstalled() { return true; } diff --git a/Modules/IGT/IGTTrackingDevices/mitkInternalTrackingTool.h b/Modules/IGT/IGTTrackingDevices/mitkInternalTrackingTool.h index fac1a6fbab..f2eb7435e4 100644 --- a/Modules/IGT/IGTTrackingDevices/mitkInternalTrackingTool.h +++ b/Modules/IGT/IGTTrackingDevices/mitkInternalTrackingTool.h @@ -1,77 +1,77 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKINTERNALTRACKINGTOOL_H_HEADER_INCLUDED_ #define MITKINTERNALTRACKINGTOOL_H_HEADER_INCLUDED_ #include #include -#include +#include #include namespace mitk { /**Documentation * \brief implements TrackingTool interface * * This class is a complete TrackingTool implementation. It can either be used directly by * TrackingDevices, or be subclassed for more specific implementations. * mitk::MicroBirdTrackingDevice uses this class to manage its tools. Other tracking devices * uses specialized versions of this class (e.g. mitk::NDITrackingTool) * * \ingroup IGT */ class MitkIGT_EXPORT InternalTrackingTool : public TrackingTool { friend class MicroBirdTrackingDevice; // Add all TrackingDevice subclasses that use InternalTrackingDevice directly public: mitkClassMacro(InternalTrackingTool, TrackingTool); virtual void GetPosition(mitk::Point3D& position) const; ///< returns the current position of the tool as an array of three floats (in the tracking device coordinate system) virtual void GetOrientation(mitk::Quaternion& orientation) const; ///< returns the current orientation of the tool as a quaternion (in the tracking device coordinate system) virtual bool Enable(); ///< enablea the tool, so that it will be tracked. Returns true if enabling was successfull virtual bool Disable(); ///< disables the tool, so that it will not be tracked anymore. Returns true if disabling was successfull virtual bool IsEnabled() const; ///< returns whether the tool is enabled or disabled virtual bool IsDataValid() const; ///< returns true if the current position data is valid (no error during tracking, tracking error below threshold, ...) virtual bool IsTooltipSet() const; ///< returns true if a tooltip is set, false if not virtual float GetTrackingError() const; ///< return one value that corresponds to the overall tracking error. The dimension of this value is specific to each tracking device virtual void SetToolName(const std::string _arg); ///< Sets the name of the tool virtual void SetToolName(const char* _arg); ///< Sets the name of the tool virtual void SetPosition(mitk::Point3D position); ///< sets the position virtual void SetOrientation(mitk::Quaternion orientation); ///< sets the orientation as a quaternion virtual void SetTrackingError(float error); ///< sets the tracking error virtual void SetDataValid(bool _arg); ///< sets if the tracking data (position & Orientation) is valid virtual void SetErrorMessage(const char* _arg); ///< sets the error message virtual void SetToolTip(mitk::Point3D toolTipPosition, mitk::Quaternion orientation = mitk::Quaternion(0,0,0,1)); ///< defines a tool tip for this tool in tool coordinates. GetPosition() and GetOrientation() return the data of the tool tip if it is defined. By default no tooltip is defined. protected: itkNewMacro(Self); InternalTrackingTool(); virtual ~InternalTrackingTool(); Point3D m_Position; ///< holds the position of the tool Quaternion m_Orientation; ///< holds the orientation of the tool float m_TrackingError; ///< holds the tracking error of the tool bool m_Enabled; ///< if true, tool is enabled and should receive tracking updates from the tracking device bool m_DataValid; ///< if true, data in m_Position and m_Orientation is valid, e.g. true tracking data Point3D m_ToolTip; Quaternion m_ToolTipRotation; bool m_ToolTipSet; }; } // namespace mitk #endif /* MITKINTERNALTRACKINGTOOL_H_HEADER_INCLUDED_ */ diff --git a/Modules/IGT/IGTTrackingDevices/mitkTrackingTool.h b/Modules/IGT/IGTTrackingDevices/mitkTrackingTool.h index 16e9e068a3..185065f6e9 100644 --- a/Modules/IGT/IGTTrackingDevices/mitkTrackingTool.h +++ b/Modules/IGT/IGTTrackingDevices/mitkTrackingTool.h @@ -1,59 +1,59 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKTRACKINGTOOL_H_HEADER_INCLUDED_ #define MITKTRACKINGTOOL_H_HEADER_INCLUDED_ #include #include #include -#include +#include #include namespace mitk { /**Documentation * \brief Interface for all Tracking Tools * * Abstract class that defines the methods that are common for all tracking tools. * * \ingroup IGT */ class MitkIGT_EXPORT TrackingTool : public itk::Object { public: mitkClassMacro(TrackingTool, itk::Object); virtual void SetToolTip(mitk::Point3D toolTipPosition, mitk::Quaternion orientation) = 0; ///< defines a tool tip for this tool in tool coordinates. GetPosition() and GetOrientation() return the data of the tool tip if it is defined. By default no tooltip is defined. virtual void GetPosition(mitk::Point3D& position) const = 0; ///< returns the current position of the tool as an array of three floats (in the tracking device coordinate system) virtual void GetOrientation(mitk::Quaternion& orientation) const = 0; ///< returns the current orientation of the tool as a quaternion in a mitk::Point4D (in the tracking device coordinate system) virtual bool Enable() = 0; ///< enables the tool, so that it will be tracked virtual bool Disable() = 0; ///< disables the tool, so that it will not be tracked anymore virtual bool IsEnabled() const = 0; ///< returns whether the tool is enabled or disabled virtual bool IsDataValid() const = 0; ///< returns true if the current position data is valid (no error during tracking, tracking error below threshold, ...) virtual float GetTrackingError() const = 0; ///< returns one value that corresponds to the overall tracking error. virtual const char* GetToolName() const; ///< every tool has a name that can be used to identify it. virtual const char* GetErrorMessage() const; ///< if the data is not valid, ErrorMessage should contain a string explaining why it is invalid (the Set-method should be implemented in subclasses, it should not be accessible by the user) protected: TrackingTool(); virtual ~TrackingTool(); std::string m_ToolName; ///< every tool has a name that can be used to identify it. std::string m_ErrorMessage; ///< if a tool is invalid, this member should contain a human readable explanation of why it is invalid itk::FastMutexLock::Pointer m_MyMutex; ///< mutex to control concurrent access to the tool }; } // namespace mitk #endif /* MITKTRACKINGTOOL_H_HEADER_INCLUDED_ */ diff --git a/Modules/IGT/IGTTrackingDevices/mitkTrackingTypes.h b/Modules/IGT/IGTTrackingDevices/mitkTrackingTypes.h index 0e4791d3eb..dc0bee3c65 100644 --- a/Modules/IGT/IGTTrackingDevices/mitkTrackingTypes.h +++ b/Modules/IGT/IGTTrackingDevices/mitkTrackingTypes.h @@ -1,253 +1,253 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKTRACKINGTYPES_H_HEADER_INCLUDED_ #define MITKTRACKINGTYPES_H_HEADER_INCLUDED_ #include #include -//#include +//#include namespace mitk { /**Documentation * \brief Error codes of NDI tracking devices */ enum NDIErrorCode { NDIOKAY = 0, NDIERROR = 1, SERIALINTERFACENOTSET, SERIALSENDERROR, SERIALRECEIVEERROR, SROMFILETOOLARGE, SROMFILETOOSMALL, NDICRCERROR, // reply has crc error, local computer detected the error NDIINVALIDCOMMAND, NDICOMMANDTOOLONG, NDICOMMANDTOOSHORT, NDICRCDOESNOTMATCH, // command had crc error, tracking device detected the error NDITIMEOUT, NDIUNABLETOSETNEWCOMMPARAMETERS, NDIINCORRECTNUMBEROFPARAMETERS, NDIINVALIDPORTHANDLE, NDIINVALIDTRACKINGPRIORITY, NDIINVALIDLED, NDIINVALIDLEDSTATE, NDICOMMANDINVALIDINCURRENTMODE, NDINOTOOLFORPORT, NDIPORTNOTINITIALIZED, NDISYSTEMNOTINITIALIZED, NDIUNABLETOSTOPTRACKING, NDIUNABLETOSTARTTRACKING, NDIINITIALIZATIONFAILED, NDIINVALIDVOLUMEPARAMETERS, NDICANTSTARTDIAGNOSTICMODE, NDICANTINITIRDIAGNOSTICS, NDIFAILURETOWRITESROM, NDIENABLEDTOOLSNOTSUPPORTED, NDICOMMANDPARAMETEROUTOFRANGE, NDINOMEMORYAVAILABLE, NDIPORTHANDLENOTALLOCATED, NDIPORTHASBECOMEUNOCCUPIED, NDIOUTOFHANDLES, NDIINCOMPATIBLEFIRMWAREVERSIONS, NDIINVALIDPORTDESCRIPTION, NDIINVALIDOPERATIONFORDEVICE, NDIWARNING, NDIUNKNOWNERROR, NDIUNEXPECTEDREPLY, UNKNOWNHANDLERETURNED, TRACKINGDEVICERESET, TRACKINGDEVICENOTSET }; /**Documentation * \brief identifier for tracking device. The way it is currently used * represents a product line rather than an actal type. Refactoring is a future option. */ enum TrackingDeviceType { NDIPolaris, ///< Polaris: optical Tracker from NDI NDIAurora, ///< Aurora: electromagnetic Tracker from NDI ClaronMicron, ///< Micron Tracker: optical Tracker from Claron IntuitiveDaVinci, ///< Intuitive Surgical: DaVinci Telemanipulator API Interface AscensionMicroBird, ///< Ascension microBird / PCIBird family VirtualTracker, ///< Virtual Tracking device class that produces random tracking coordinates TrackingSystemNotSpecified,///< entry for not specified or initialized tracking system TrackingSystemInvalid ///< entry for invalid state (mainly for testing) }; /**Documentation * \brief Error codes of NDI tracking devices */ enum OperationMode { ToolTracking6D, ToolTracking5D, MarkerTracking3D, HybridTracking }; /** * \brief This enum is deprecated. In future, please use the new TrackingDeviceData to model Specific tracking Volumes * Represents the setting of the tracking volume of a NDI tracking device. The tracking volume of * a tracking device itself (as 3d-Object) is represented by an instance of the class mitk::TrackingVolume * as defined by NDI API SFLIST (Aurora and Polaris API guide) * */ enum NDITrackingVolume { Standard, Pyramid, SpectraPyramid, VicraVolume, Cube, Dome }; /** * /brief This structure defines key variables of a device model and type. * It is specifically used to find out which models belong to which vendor, and what volume * to use for a specific Model. Leaving VolumeModelLocation set to null will instruct the Generator * to generate a field to the best of his ability */ struct TrackingDeviceData { TrackingDeviceType Line; std::string Model; std::string VolumeModelLocation; }; /** * Here all supported devices are defined. Dont forget to introduce new Devices into the TrackingDeviceList Array at the bottom! * If a model does not have a corresponding tracking volume yet, pass an empty string to denote "No Model". pass "cube" to render * a default cube of 400x400 px. You can define additional magic strings in the TrackingVolumeGenerator. */ static TrackingDeviceData DeviceDataAuroraCompact = {NDIAurora, "Aurora Compact", "NDIAuroraCompactFG_Dome.stl"}; static TrackingDeviceData DeviceDataAuroraPlanarCube = {NDIAurora, "Aurora Planar (Cube)", "NDIAurora.stl"}; static TrackingDeviceData DeviceDataAuroraPlanarDome = {NDIAurora, "Aurora Planar (Dome)","NDIAuroraPlanarFG_Dome.stl"}; static TrackingDeviceData DeviceDataAuroraTabletop = {NDIAurora, "Aurora Tabletop", "NDIAuroraTabletopFG_Dome.stl"}; // The following entry is for the tabletop prototype, which had an lower barrier of 8cm. The new version has a lower barrier of 12cm. //static TrackingDeviceData DeviceDataAuroraTabletopPrototype = {NDIAurora, "Aurora Tabletop Prototype", "NDIAuroraTabletopFG_Prototype_Dome.stl"}; static TrackingDeviceData DeviceDataMicronTrackerH40 = {ClaronMicron, "Micron Tracker H40", "ClaronMicron.stl"}; static TrackingDeviceData DeviceDataPolarisSpectra = {NDIPolaris, "Polaris Spectra", "NDIPolaris.stl"}; static TrackingDeviceData DeviceDataPolarisVicra = {NDIPolaris, "Polaris Vicra", "NDIPolarisVicra.stl"}; static TrackingDeviceData DeviceDataDaVinci = {IntuitiveDaVinci, "Intuitive DaVinci", "IntuitiveDaVinci.stl"}; static TrackingDeviceData DeviceDataMicroBird = {AscensionMicroBird, "Ascension MicroBird", ""}; static TrackingDeviceData DeviceDataVirtualTracker = {VirtualTracker, "Virtual Tracker", "cube"}; static TrackingDeviceData DeviceDataUnspecified = {TrackingSystemNotSpecified, "Unspecified System", "cube"}; // Careful when changing the "invalid" device: The mitkTrackingTypeTest is using it's data. static TrackingDeviceData DeviceDataInvalid = {TrackingSystemInvalid, "Invalid Tracking System", ""}; static TrackingDeviceData TrackingDeviceList[] = {DeviceDataAuroraPlanarCube, DeviceDataAuroraPlanarDome, DeviceDataAuroraCompact, DeviceDataAuroraTabletop, DeviceDataMicronTrackerH40, DeviceDataPolarisSpectra, DeviceDataPolarisVicra, DeviceDataDaVinci, DeviceDataMicroBird, DeviceDataVirtualTracker, DeviceDataUnspecified, DeviceDataInvalid}; /** * /brief Returns all devices compatibel to the given Line of Devices */ static std::vector GetDeviceDataForLine(TrackingDeviceType Type){ std::vector Result; int size = (sizeof (TrackingDeviceList) / sizeof*(TrackingDeviceList)); for(int i=0; i < size; i++) { if(TrackingDeviceList[i].Line == Type ) Result.push_back(TrackingDeviceList[i]); } return Result; } /** * /brief Returns the first TracingDeviceData mathing a given line. Useful for backward compatibility * with the old way to manage Devices */ static TrackingDeviceData GetFirstCompatibleDeviceDataForLine(TrackingDeviceType Type){ return GetDeviceDataForLine(Type).front(); } /** * /brief Returns the device Data set matching the model name or the invalid device, if none was found */ static TrackingDeviceData GetDeviceDataByName(std::string modelName){ int size = (sizeof (TrackingDeviceList) / sizeof*(TrackingDeviceList)); for(int i=0; i < size; i++) { if(TrackingDeviceList[i].Model == modelName) return TrackingDeviceList[i]; } return DeviceDataInvalid; } /**Documentation * \brief activation rate of IR illuminator for NDI Polaris tracking device */ enum IlluminationActivationRate { Hz20 = 20, Hz30 = 30, Hz60 = 60 }; /**Documentation * \brief Data transfer mode for NDI tracking devices */ enum DataTransferMode { TX = 0, BX = 1 }; /**Documentation * \brief Query mode for NDI tracking devices */ enum PHSRQueryType { ALL = 0x00, FREED = 0x01, OCCUPIED = 0x02, INITIALIZED = 0x03, ENABLED = 0x04 }; typedef itk::Point MarkerPointType; typedef std::vector MarkerPointContainerType; /** * \brief Defines the tools (arms) of the daVinci system: * PSM1 - Patient side manipulator 1 * PSM2 - Patient side manipulator 2 * ECM - Endoscopic camera manipulator * MTML - Left master target manipulator * MTMR - Right master target manipulator * PSM - Patient side manipulator 3 (if not existent, its data will always be zero) **/ enum DaVinciToolType { PSM1 = 0, PSM2 = 1, ECM = 2, MTML = 3, MTMR = 4, PSM = 5, //UIEvents = 6, }; } // namespace mitk #endif /* MITKTRACKINGTYPES_H_HEADER_INCLUDED_ */ diff --git a/Modules/IGT/IGTTrackingDevices/mitkVirtualTrackingTool.h b/Modules/IGT/IGTTrackingDevices/mitkVirtualTrackingTool.h index 732044affd..d7e5abaa67 100644 --- a/Modules/IGT/IGTTrackingDevices/mitkVirtualTrackingTool.h +++ b/Modules/IGT/IGTTrackingDevices/mitkVirtualTrackingTool.h @@ -1,73 +1,73 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKVirtualTrackingTool_H_HEADER_INCLUDED_ #define MITKVirtualTrackingTool_H_HEADER_INCLUDED_ #include #include -#include +#include #include //#if ITK_VERSION_MAJOR == 3 && ITK_VERSION_MINOR == 18 && ITK_VERSION_PATCH == 0 // #include // fixed version of a class that is defect in ITK 3.18 //#else // #include //#endif #include namespace mitk { /**Documentation * \brief implements TrackingTool interface * * This class is a complete TrackingTool implementation. It can either be used directly by * TrackingDevices, or be subclassed for more specific implementations. * mitk::MicroBirdTrackingDevice uses this class to manage its tools. Other tracking devices * uses specialized versions of this class (e.g. mitk::NDITrackingTool) * * \ingroup IGT */ class MitkIGT_EXPORT VirtualTrackingTool : public InternalTrackingTool { public: mitkClassMacro(VirtualTrackingTool, InternalTrackingTool); friend class VirtualTrackingDevice; typedef itk::NonUniformBSpline<3> SplineType; ///< spline type used for tool path interpolation itkGetMacro(SplineLength, mitk::ScalarType); itkSetMacro(SplineLength, mitk::ScalarType); itkGetMacro(Velocity, mitk::ScalarType); itkSetMacro(Velocity, mitk::ScalarType); itkGetObjectMacro(Spline, SplineType); protected: itkNewMacro(Self); VirtualTrackingTool(); virtual ~VirtualTrackingTool(); SplineType::Pointer m_Spline; mitk::ScalarType m_SplineLength; mitk::ScalarType m_Velocity; }; } // namespace mitk #endif /* MITKVirtualTrackingTool_H_HEADER_INCLUDED_ */ diff --git a/Modules/IGT/Testing/mitkNavigationDataToMessageFilterTest.cpp b/Modules/IGT/Testing/mitkNavigationDataToMessageFilterTest.cpp index c0553c159f..1d9af599ca 100644 --- a/Modules/IGT/Testing/mitkNavigationDataToMessageFilterTest.cpp +++ b/Modules/IGT/Testing/mitkNavigationDataToMessageFilterTest.cpp @@ -1,229 +1,229 @@ /*=================================================================== 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 "mitkNavigationDataToMessageFilter.h" #include "mitkNavigationData.h" #include "mitkTestingMacros.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include // Receiver class remembers Messages received. // Will tell about received Messages when asked. class MessageReceiverClass { public: MessageReceiverClass(unsigned int numberOfNavigationDatas) { m_ReceivedData.resize(numberOfNavigationDatas); for (unsigned int i = 0; i < numberOfNavigationDatas; ++i) m_ReceivedData[i] = mitk::NavigationData::New(); m_MessagesReceived = 0; } void OnPositionChanged(mitk::NavigationData::PositionType v, unsigned int index) { m_ReceivedData[index]->SetPosition(v); ++m_MessagesReceived; } void OnOrientationChanged(mitk::NavigationData::OrientationType v, unsigned int index) { m_ReceivedData[index]->SetOrientation(v); ++m_MessagesReceived; } void OnErrorChanged(mitk::NavigationData::CovarianceMatrixType v, unsigned int index) { m_ReceivedData[index]->SetCovErrorMatrix(v); ++m_MessagesReceived; } void OnTimeStampChanged(mitk::NavigationData::TimeStampType v, unsigned int index) { m_ReceivedData[index]->SetIGTTimeStamp(v); ++m_MessagesReceived; } void OnDataValidChanged(bool v, unsigned int index) { m_ReceivedData[index]->SetDataValid(v); ++m_MessagesReceived; } std::vector m_ReceivedData; int m_MessagesReceived; }; /**Documentation * test for the class "NavigationDataToMessageFilter". */ int mitkNavigationDataToMessageFilterTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("NavigationDataToMessageFilter"); /* first tests with one input */ { // let's create an object of our class mitk::NavigationDataToMessageFilter::Pointer myFilter = mitk::NavigationDataToMessageFilter::New(); // first test: did this work? // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since // it makes no sense to continue without an object. MITK_TEST_CONDITION_REQUIRED(myFilter.IsNotNull(),"Testing instantiation"); /* create helper objects: navigation data with position as origin, zero quaternion, zero error and data valid */ mitk::NavigationData::PositionType initialPos; mitk::FillVector3D(initialPos, 1.0, 2.0, 3.0); mitk::NavigationData::OrientationType initialOri(1.0, 2.0, 3.0, 4.0); mitk::NavigationData::Pointer nd1 = mitk::NavigationData::New(); nd1->SetPosition(initialPos); nd1->SetOrientation(initialOri); nd1->SetPositionAccuracy(11.111); nd1->SetIGTTimeStamp(64.46); nd1->SetDataValid(true); myFilter->SetInput(nd1); MITK_TEST_CONDITION(myFilter->GetInput() == nd1, "testing Set-/GetInput()"); mitk::NavigationData* output = myFilter->GetOutput(); MITK_TEST_CONDITION_REQUIRED(output != NULL, "Testing GetOutput()"); /* register message receiver */ MessageReceiverClass answers(1); myFilter->AddPositionChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnPositionChanged)); myFilter->AddOrientationChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnOrientationChanged)); myFilter->AddErrorChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnErrorChanged)); myFilter->AddTimeStampChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnTimeStampChanged)); myFilter->AddDataValidChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnDataValidChanged)); output->Update(); // execute filter MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[0]->GetPosition(), nd1->GetPosition()), "Testing PositionChanged message"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[0]->GetOrientation(), nd1->GetOrientation()), "Testing OrientationChanged message"); MITK_TEST_CONDITION( answers.m_ReceivedData[0]->GetCovErrorMatrix() == nd1->GetCovErrorMatrix(), "Testing ErrorChanged message"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[0]->GetIGTTimeStamp(), nd1->GetIGTTimeStamp()), "Testing TimeStampChanged message"); MITK_TEST_CONDITION( answers.m_ReceivedData[0]->IsDataValid() == nd1->IsDataValid(), "Testing PositionChanged message"); MITK_TEST_CONDITION( answers.m_MessagesReceived == 5, "Correct number of messages send?"); /* change one input parameter */ nd1->SetDataValid(false); output->Update(); // re-execute filter MITK_TEST_CONDITION( answers.m_ReceivedData[0]->IsDataValid() == nd1->IsDataValid(), "Testing PositionChanged message"); MITK_TEST_CONDITION( answers.m_MessagesReceived == 6, "only necessary messages send?"); // only datavalid message re-send /* changing two input parameters */ mitk::FillVector3D(initialPos, 11.0, 21.0, 31.0); nd1->SetPosition(initialPos); // change only one parameter nd1->SetIGTTimeStamp(55.55); // change only one parameter output->Update(); // re-execute filter MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[0]->GetPosition(), nd1->GetPosition()), "Testing PositionChanged message"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[0]->GetIGTTimeStamp(), nd1->GetIGTTimeStamp()), "Testing TimeStampChanged message"); MITK_TEST_CONDITION( answers.m_MessagesReceived == 8, "only necessary messages send?"); // only 2 new messages send /* try to add a second input */ //MITK_TEST_OUTPUT_NO_ENDL( << "Exception on adding second input? --> "); //mitk::NavigationData::Pointer nd2 = mitk::NavigationData::New(); //MITK_TEST_FOR_EXCEPTION(std::invalid_argument, myFilter->SetInput(1, nd2)); } /* now test with multiple inputs */ { MITK_TEST_OUTPUT( << "Now, perform tests with multiple inputs"); mitk::NavigationDataToMessageFilter::Pointer myFilter = mitk::NavigationDataToMessageFilter::New(); /* create helper objects: navigation data with position as origin, zero quaternion, zero error and data valid */ mitk::NavigationData::PositionType initialPos; mitk::FillVector3D(initialPos, 1.0, 1.0, 1.0); mitk::NavigationData::OrientationType initialOri(1.0, 1.0, 1.0, 1.0); mitk::NavigationData::Pointer nd0 = mitk::NavigationData::New(); nd0->SetPosition(initialPos); nd0->SetOrientation(initialOri); nd0->SetPositionAccuracy(11.111); nd0->SetIGTTimeStamp(64.46); nd0->SetDataValid(true); mitk::FillVector3D(initialPos, 2.0, 2.0, 2.0); mitk::NavigationData::OrientationType initialOri2(1.0, 1.0, 1.0, 1.0); mitk::NavigationData::Pointer nd1 = mitk::NavigationData::New(); nd1->SetPosition(initialPos); nd1->SetOrientation(initialOri2); nd1->SetPositionAccuracy(22.222); nd1->SetIGTTimeStamp(222.2); nd1->SetDataValid(true); myFilter->SetInput(0, nd0); myFilter->SetInput(1, nd1); MITK_TEST_CONDITION(myFilter->GetInput(0) == nd0, "testing Set-/GetInput(0)"); MITK_TEST_CONDITION(myFilter->GetInput(1) == nd1, "testing Set-/GetInput(1)"); mitk::NavigationData* output0 = myFilter->GetOutput(); mitk::NavigationData* output1 = myFilter->GetOutput(1); MITK_TEST_CONDITION_REQUIRED(output0 != NULL, "Testing GetOutput()"); MITK_TEST_CONDITION_REQUIRED(output1 != NULL, "Testing GetOutput(1)"); /* register message receiver */ MessageReceiverClass answers(2); myFilter->AddPositionChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnPositionChanged)); myFilter->AddOrientationChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnOrientationChanged)); myFilter->AddErrorChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnErrorChanged)); myFilter->AddTimeStampChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnTimeStampChanged)); myFilter->AddDataValidChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnDataValidChanged)); output0->Update(); // execute filter. This should send messages for both inputs MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[0]->GetPosition(), nd0->GetPosition()), "Testing PositionChanged message"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[0]->GetOrientation(), nd0->GetOrientation()), "Testing OrientationChanged message"); MITK_TEST_CONDITION( answers.m_ReceivedData[0]->GetCovErrorMatrix() == nd0->GetCovErrorMatrix(), "Testing ErrorChanged message"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[0]->GetIGTTimeStamp(), nd0->GetIGTTimeStamp()), "Testing TimeStampChanged message"); MITK_TEST_CONDITION( answers.m_ReceivedData[0]->IsDataValid() == nd0->IsDataValid(), "Testing PositionChanged message"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[1]->GetPosition(), nd1->GetPosition()), "Testing PositionChanged message"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[1]->GetOrientation(), nd1->GetOrientation()), "Testing OrientationChanged message"); MITK_TEST_CONDITION( answers.m_ReceivedData[1]->GetCovErrorMatrix() == nd1->GetCovErrorMatrix(), "Testing ErrorChanged message"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[1]->GetIGTTimeStamp(), nd1->GetIGTTimeStamp()), "Testing TimeStampChanged message"); MITK_TEST_CONDITION( answers.m_ReceivedData[1]->IsDataValid() == nd1->IsDataValid(), "Testing PositionChanged message"); MITK_TEST_CONDITION( answers.m_MessagesReceived == 10, "Correct number of messages send?"); MITK_TEST_OUTPUT( << "answers.m_MessagesReceived = " << answers.m_MessagesReceived); /* change one input parameter */ nd0->SetDataValid(false); output0->Update(); // re-execute filter MITK_TEST_CONDITION( answers.m_ReceivedData[0]->IsDataValid() == nd0->IsDataValid(), "Testing PositionChanged message for input 0"); MITK_TEST_CONDITION( answers.m_MessagesReceived == 11, "only necessary messages send?"); // only datavalid message for input 0 re-send /* remove one listener and check that message is not send */ myFilter->RemoveTimeStampChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnTimeStampChanged)); mitk::NavigationData::TimeStampType oldValue = nd1->GetIGTTimeStamp(); nd1->SetIGTTimeStamp(999.9); myFilter->Update(); MITK_TEST_CONDITION( ! mitk::Equal(answers.m_ReceivedData[1]->GetIGTTimeStamp(), nd1->GetIGTTimeStamp()), "Testing if TimeStamp message is _not_ send after RemoveListener (!= new value)"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[1]->GetIGTTimeStamp(), oldValue), "Testing if TimeStamp message is _not_ send after RemoveListener (== old value)"); MITK_TEST_CONDITION( answers.m_MessagesReceived == 11, "no new messages send?"); // no new message send? /* other messages are still send? */ nd1->SetDataValid(false); myFilter->Update(); MITK_TEST_CONDITION( answers.m_ReceivedData[1]->IsDataValid() == nd1->IsDataValid(), "Other messages still send? ->Testing PositionChanged message for input 1 again"); MITK_TEST_CONDITION( answers.m_MessagesReceived == 12, "only necessary messages send?"); // only DataValid message for input 1 re-send /* check if other output still has its old value */ MITK_TEST_CONDITION( answers.m_ReceivedData[0]->IsDataValid() == nd0->IsDataValid(), "Testing PositionChanged message for input 0"); } // The end MITK_TEST_END(); } diff --git a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorAddOn.cpp b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorAddOn.cpp index 13a3ab6f00..7f885f3778 100644 --- a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorAddOn.cpp +++ b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorAddOn.cpp @@ -1,61 +1,61 @@ /*=================================================================== 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 #include -#include +#include #include #include #include mitk::SpaceNavigatorAddOn* mitk::SpaceNavigatorAddOn::GetInstance() { // only needed for initializiation SpaceNavigatorDriver* spaceNavigatorDriver = SpaceNavigatorDriver::GetInstance(); static SpaceNavigatorAddOn instance; return &instance; } void mitk::SpaceNavigatorAddOn::DeviceChange (long device, long keys, long programmableKeys) { } void mitk::SpaceNavigatorAddOn::KeyDown (int keyCode) { mitk::Event* e = new mitk::Event(NULL, mitk::Type_SpaceNavigatorKeyDown, mitk::BS_LeftButton, keyCode, mitk::Key_none); mitk::StateEvent* se = new mitk::StateEvent(mitk::EIDSPACENAVIGATORKEYDOWN, e); this->ForwardEvent(se); } void mitk::SpaceNavigatorAddOn::KeyUp (int keyCode) { } void mitk::SpaceNavigatorAddOn::SensorInput( mitk::Vector3D translation, mitk::Vector3D rotation, mitk::ScalarType angle) { mitk::SpaceNavigatorEvent* e = new mitk::SpaceNavigatorEvent(mitk::BS_NoButton, translation, rotation, angle); mitk::StateEvent* se = new mitk::StateEvent(mitk::EIDSPACENAVIGATORINPUT, e); this->ForwardEvent(se); } diff --git a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorAddOn.h b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorAddOn.h index e6810bc952..c26eca8b5e 100644 --- a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorAddOn.h +++ b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorAddOn.h @@ -1,78 +1,78 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKSPACENAVIGATORADDON_H_HEADER_INCLUDED #define MITKSPACENAVIGATORADDON_H_HEADER_INCLUDED -#include +#include #include #include #include namespace mitk { /** * Documentation in the interface. * * @brief EventMapper addon for a 3DConnexion Space Navigator * @ingroup Interaction */ class mitkSpaceNavigator_EXPORT SpaceNavigatorAddOn : public EventMapperAddOn { public: // Singleton static SpaceNavigatorAddOn* GetInstance(); /** * @noimplement not needed */ void DeviceChange (long device, long keys, long programmableKeys); /** * If a button is pressed down an event is fired. * * @param keyCode the id to the key, that is pressed */ void KeyDown (int keyCode); /** * @noimplement not needed */ void KeyUp (int keyCode); /** * Reacts on any movement of the mouse and fires events accordingly. * * @param translation * the translation of the mouse as an 3D vector * @param rotation * the rotation of the mouse as an 3D vector * @param angle * the angle from the mouse as an scalar unit */ void SensorInput(mitk::Vector3D translation, mitk::Vector3D rotation, mitk::ScalarType angle); protected: private: }; // end class SpaceNavigatorAddOn } // end namespace mitk #endif // MITKSPACENAVIGATORADDON_H_HEADER_INCLUDED diff --git a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorDriver.h b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorDriver.h index fedf2a62eb..a2111bffc7 100644 --- a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorDriver.h +++ b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorDriver.h @@ -1,96 +1,96 @@ /*=================================================================== 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 #ifndef SpaceNavigatorDriver__h__ #define SpaceNavigatorDriver__h__ #ifdef SPACE_NAVIGATOR_MAIN_SOURCE #define _ATL_ATTRIBUTES 1 #define _WIN32_DCOM #include #include #include #include #include #include // if the error C2813 occurs // just remove /MP suffix: the problem is that // the #import statement is not yet compatible [05-11-2010] // check the microsoft homepage for further information #import "progid:TDxInput.Device" embedded_idl no_namespace using namespace ATL; -#include +#include #include using std::cout; using std::endl; [module(name="mitkInputDevices")]; [ event_receiver(com) ] class SpaceNavigatorDriver { public: static SpaceNavigatorDriver* GetInstance(); private: SpaceNavigatorDriver(); ~SpaceNavigatorDriver(); //methods for workaround of .net 2003 compiler Artikel-ID : 829749 //http://support.microsoft.com/kb/829749/de inline HRESULT HookEvent1(CComPtr device); inline HRESULT HookEvent2(); inline HRESULT HookEvent3(CComPtr device); inline HRESULT HookEvent4(); inline HRESULT HookEvent5(); #if 1 CComPtr m_pISensor; CComPtr m_pIKeyboard; #else ISensorPtr m_pISensor; IKeyboardPtr m_pIKeyboard; #endif public: // COM Event handlers HRESULT InitializeCOM(); HRESULT OnDeviceChange (long reserved); HRESULT OnKeyDown (int keyCode); HRESULT OnKeyUp (int keyCode); HRESULT OnSensorInput(void); HRESULT UninitializeCOM(); }; #else // SPACE_NAVIGATOR_MAIN_SOURCE class SpaceNavigatorDriver { public: static SpaceNavigatorDriver* GetInstance(); }; #endif #endif // SpaceNavigatorDriver__h__ diff --git a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorEvent.cpp b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorEvent.cpp index 458c2ed902..82bec99cb0 100644 --- a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorEvent.cpp +++ b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorEvent.cpp @@ -1,25 +1,25 @@ /*=================================================================== 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 "mitkSpaceNavigatorEvent.h" #include "mitkInteractionConst.h" -#include "mitkVector.h" +#include "mitkTypes.h" mitk::SpaceNavigatorEvent::SpaceNavigatorEvent(int buttonState, const Vector3D& translation, const Vector3D& rotation, const ScalarType& angle) : Event(NULL, mitk::Type_SpaceNavigatorInput, BS_NoButton, buttonState, Key_none), m_Translation(translation), m_Rotation(rotation), m_Angle(angle) { } diff --git a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorEvent.h b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorEvent.h index 2a96ee8b13..e44d52b1bd 100644 --- a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorEvent.h +++ b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorEvent.h @@ -1,94 +1,94 @@ /*=================================================================== 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. ===================================================================*/ #ifndef SPACENAVIGATOREVENT_H_ #define SPACENAVIGATOREVENT_H_ #include #include -#include +#include #include namespace mitk { /** * Documentation * @brief Event on 3D Mouse input * * Seven coordinates exposed by the 3D Mouse: * 3-dimensional translation vector * 3-dimensional rotation achsis (length allways 1.0) * scalar rotation angle * * @ingroup Interaction */ class mitkSpaceNavigator_EXPORT SpaceNavigatorEvent : public Event { public: /** * @brief Constructor with all necessary arguments (for further information about the parameter:
* mitk::SpaceNavigatorAddOn. * * @param buttonState information from the Event * */ SpaceNavigatorEvent(int buttonState, const Vector3D& translation, const Vector3D& rotation, const ScalarType& angle); //Getter and Setter const Vector3D& GetTranslation() const { return m_Translation; } void SetTranslation(const Vector3D& translation) { m_Translation = translation; } const Vector3D& GetRotation() const { return m_Rotation; } void SetRotation(const Vector3D& rotation) { m_Rotation = rotation; } const ScalarType& GetAngle() const { return m_Angle; } void SetAngle(const ScalarType& angle) { m_Angle = angle; } protected: Vector3D m_Translation; Vector3D m_Rotation; ScalarType m_Angle; }; // end class SpaceNavigatorEvent } // end namespace mitk #endif /* SPACENAVIGATOREVENT_H_ */ diff --git a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorVtkCameraController.cpp b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorVtkCameraController.cpp index 9cbf690990..3de113e61b 100644 --- a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorVtkCameraController.cpp +++ b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorVtkCameraController.cpp @@ -1,238 +1,238 @@ /*=================================================================== 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 "mitkSpaceNavigatorVtkCameraController.h" #include "mitkVtkPropRenderer.h" #include "vtkCamera.h" #include "vtkRenderer.h" #include "vtkTransform.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkInteractionConst.h" #include "mitkStateEvent.h" #include "mitkGlobalInteraction.h" #include "vtkMath.h" #include const double TRANSLATIONSENSITIVITY = 2.0; const double ROTATIONSENSIVITY = 3.5; const double ANGLESENSITIVITY = 3.5; mitk::SpaceNavigatorVtkCameraController::SpaceNavigatorVtkCameraController() : CameraController("SpaceNavigatorInteraction") { //connect method this->OnSpaceNavigatorEvent to StateMachineEventMechanism CONNECT_ACTION(AcONSPACENAVIGATORMOUSEINPUT, OnSpaceNavigatorEvent); CONNECT_ACTION(AcONPACENAVIGATORKEYDOWN, OnSpaceNavigatorKeyDown); m_ClippingRangeIsSet = false; } mitk::SpaceNavigatorVtkCameraController::~SpaceNavigatorVtkCameraController() { } bool mitk::SpaceNavigatorVtkCameraController::OnSpaceNavigatorEvent(mitk::Action* a, const mitk::StateEvent* e) { //only if 3D rendering const mitk::BaseRenderer* br = mitk::GlobalInteraction::GetInstance()->GetFocus(); this->SetRenderer( br ); mitk::BaseRenderer::MapperSlotId id = ((mitk::BaseRenderer*)(br))->GetMapperID(); if (id != mitk::BaseRenderer::Standard3D) return true; //only if focused by the FocusManager if (this->GetRenderer() != mitk::GlobalInteraction::GetInstance()->GetFocus()) return true; //pre-checking for safety vtkRenderer* vtkRenderer = ((mitk::VtkPropRenderer*)this->GetRenderer())->GetVtkRenderer(); if (vtkRenderer == NULL) return false; vtkCamera* vtkCam = (vtkCamera*)vtkRenderer->GetActiveCamera(); if(!m_ClippingRangeIsSet) vtkCam->SetClippingRange(0.1, 1000000); const mitk::SpaceNavigatorEvent* snevent = dynamic_cast(e->GetEvent()); if (snevent == NULL) { MITK_ERROR <<"Wrong event for SpaceNavigatorVtkCameraController!"; return false; } //get the information from the mouse mitk::Vector3D translation = snevent->GetTranslation(); mitk::Vector3D rotation = snevent->GetRotation(); mitk::ScalarType angle = snevent->GetAngle(); //output for debug //std::cout<<"translation: "<GetDataStorage(); mitk::BoundingBox::Pointer bb = ds->ComputeBoundingBox(); mitk::BoundingBox::AccumulateType length = bb->GetDiagonalLength2(); if (length > 0.00001)//if length not zero sceneSensivity *= 100.0 / (sqrt(length)) ; //sensivity to adapt to mitk speed translation *= sceneSensivity * TRANSLATIONSENSITIVITY; rotation *= sceneSensivity * ROTATIONSENSIVITY; angle *= sceneSensivity * ANGLESENSITIVITY; //compute the global space coordinates from the relative mouse coordinate //first we need the position of the camera mitk::Vector3D camPosition; double camPositionTemp[3]; vtkCam->GetPosition(camPositionTemp); camPosition[0] = camPositionTemp[0]; camPosition[1] = camPositionTemp[1]; camPosition[2] = camPositionTemp[2]; //then the upvector of the camera mitk::Vector3D upCamVector; double upCamTemp[3]; vtkCam->GetViewUp(upCamTemp); upCamVector[0] = upCamTemp[0]; upCamVector[1] = upCamTemp[1]; upCamVector[2] = upCamTemp[2]; upCamVector.Normalize(); //then the vector to which the camera is heading at (focalpoint) mitk::Vector3D focalPoint; double focalPointTemp[3]; vtkCam->GetFocalPoint(focalPointTemp); focalPoint[0] = focalPointTemp[0]; focalPoint[1] = focalPointTemp[1]; focalPoint[2] = focalPointTemp[2]; mitk::Vector3D focalVector; focalVector = focalPoint - camPosition; focalVector.Normalize(); //orthogonal vector to focalVector and upCamVector mitk::Vector3D crossVector; crossVector = CrossProduct(upCamVector, focalVector); crossVector.Normalize(); //now we have the current orientation so we can adapt it according to the current information, which we got from the TDMouse //new position of the camera: //left/right = camPosition + crossVector * translation[0]; mitk::Vector3D vectorX = crossVector * -translation[0]; //changes the magnitude, not the direction double nextCamPosition[3]; nextCamPosition[0] = camPosition[0] + vectorX[0]; nextCamPosition[1] = camPosition[1] + vectorX[1]; nextCamPosition[2] = camPosition[2] + vectorX[2]; //now the up/down movement mitk::Vector3D vectorY = upCamVector * translation[1]; //changes the magnitude, not the direction nextCamPosition[0] += vectorY[0]; nextCamPosition[1] += vectorY[1]; nextCamPosition[2] += vectorY[2]; //forward/backward movement mitk::Vector3D vectorZ = focalVector * -translation[2]; //changes the magnitude, not the direction nextCamPosition[0] += vectorZ[0]; nextCamPosition[1] += vectorZ[1]; nextCamPosition[2] += vectorZ[2]; //set the next position double nextPosition[3]; nextPosition[0] = nextCamPosition[0]; nextPosition[1] = nextCamPosition[1]; nextPosition[2] = nextCamPosition[2]; vtkCam->SetPosition(nextPosition); //adapt the focal point the same way double currentFocalPoint[3], nextFocalPoint[3]; vtkCam->GetFocalPoint(currentFocalPoint); nextFocalPoint[0] = currentFocalPoint[0] + vectorX[0] + vectorY[0] + vectorZ[0]; nextFocalPoint[1] = currentFocalPoint[1] + vectorX[1] + vectorY[1] + vectorZ[1]; ; nextFocalPoint[2] = currentFocalPoint[2] + vectorX[2] + vectorY[2] + vectorZ[2]; vtkCam->SetFocalPoint(nextFocalPoint); //now adapt the rotation of the mouse and adapt the camera according to it //Pitch: //Rotate the focal point about the cross product of the view up vector and the direction of //projection, centered at the camera's position. vtkCam->Pitch(rotation[0]*angle); //Yaw: //Rotate the focal point about the view up vector centered at the camera's position. //Note that the view up vector is not necessarily perpendicular to the direction of projection. vtkCam->Yaw(rotation[1]*angle); //Roll: //Rotate the camera about the direction of projection. vtkCam->Roll(-rotation[2]*angle * 1.5);//*1.5 to speed up the rotation[2] a little bit //Recompute the ViewUp vector to force it to be perpendicular to camera->focalpoint vector. //Unless you are going to use Yaw or Azimuth on the camera, there is no need to do this. vtkCam->OrthogonalizeViewUp(); //no zooming, only translating to the front or back // dolly: Move the position of the camera along the direction // of projection. Moving towards the focal point (e.g., greater // than 1) is a dolly-in, moving away from the focal point // (e.g., less than 1) is a dolly-out. //double distance = ((tdevent->GetTranslation())[1] / 10.0);//make it less sensitive in comparison to translation and rotatipn //vtkCam->Dolly(1.0 + distance ); //Reset the camera clipping range based on the bounds of the visible actors. //This ensures that no props are cut off vtkRenderer->ResetCameraClippingRange(); mitk::RenderingManager::GetInstance()->ForceImmediateUpdate(mitk::GlobalInteraction::GetInstance()->GetFocus()->GetRenderWindow()); return true; } bool mitk::SpaceNavigatorVtkCameraController::OnSpaceNavigatorKeyDown(mitk::Action* a, const mitk::StateEvent* e) { //reset the camera, so that the objects shown in the scene can be seen. const mitk::VtkPropRenderer* glRenderer = dynamic_cast(m_Renderer); if (glRenderer) { vtkRenderer* vtkRenderer = glRenderer->GetVtkRenderer(); mitk::DataStorage* ds = m_Renderer->GetDataStorage(); if (ds == NULL) return false; mitk::BoundingBox::Pointer bb = ds->ComputeBoundingBox(); mitk::Point3D middle =bb->GetCenter(); vtkRenderer->GetActiveCamera()->SetFocalPoint(middle[0],middle[1],middle[2]); vtkRenderer->ResetCamera(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return true; } return false; } diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteAddOn.h b/Modules/InputDevices/WiiMote/mitkWiiMoteAddOn.h index 5a5f7fbe62..d6d29a1835 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteAddOn.h +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteAddOn.h @@ -1,104 +1,104 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITK_WIIMOTEADDON_H_ #define MITK_WIIMOTEADDON_H_ // export macro #include // mitk -#include "mitkVector.h" // used for Point2D +#include "mitkTypes.h" // used for Point2D #include namespace mitk { class WiiMoteThread; /** * Documentation in the interface. Some code snippets used here are from the demo
* application from gl.tter and therefore are under the same license as wiimote.cpp . * * @brief EventMapper addon for a Wiimote * @ingroup Interaction */ class mitkWiiMote_EXPORT WiiMoteAddOn : public EventMapperAddOn { public: WiiMoteAddOn(); ~WiiMoteAddOn(); // Singleton static WiiMoteAddOn* GetInstance(); /** * Starts all available Wiimotes. */ void ActivateWiiMotes(); /** * Disconnects all Wiimotes and stops the thread. */ void DeactivateWiiMotes(); /** * Creates suitable events, when the Wiimote sends IR data
* for movement and forwards it for further processing. */ void WiiMoteInput(const itk::EventObject& e); /** * Creates suitable events, when the Wiimote sends button events
* to trigger an action and forwards it for further processing. */ void WiiMoteButtonPressed(const itk::EventObject& e); /** * Creates suitable events, when the Wiimote sends button events
* to trigger an action and forwards it for further processing. */ void WiiMoteButtonReleased(const itk::EventObject& e); /** * Creates suitable events, when the Wiimote sends IR data
* to configure the sensitivity and forwards it for further processing. */ void WiiMoteCalibrationInput(const itk::EventObject& e); /** * @see mitk::WiiMoteThread::SetWiiMoteSurfaceIModus(bool activated) */ void SetWiiMoteSurfaceIModus(bool activated); /** * Creates suitable events, regardless what type of data the
* Wiimote sends for a surface interaction. Then forwards the
* transformed data for further processing. * */ void WiiMoteSurfaceInteractionInput(const itk::EventObject& e); protected: private: WiiMoteThread* m_WiiMoteThread; }; // end class WiiMoteAddOn } // end namespace mitk #endif // MITK_WIIMOTEADDON_H_ diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteButtonEvent.h b/Modules/InputDevices/WiiMote/mitkWiiMoteButtonEvent.h index c48e92f1f1..3cccc2a4c2 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteButtonEvent.h +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteButtonEvent.h @@ -1,58 +1,58 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITK_WIIMOTEBUTTONEVENT_H #define MITK_WIIMOTEBUTTONEVENT_H #include "mitkEvent.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkInteractionConst.h" #include "mitkWiiMoteExports.h" namespace mitk { /** * This event type is used for button events triggered by the
* the Wiimote driver. */ class mitkWiiMote_EXPORT WiiMoteButtonEvent : public Event, itk::EventObject { public: typedef WiiMoteButtonEvent Self; typedef itk::EventObject Superclass; /** * Initializes a Wiimote Event, that stores additional information.
* * @see mitk::Event::Event(mitk::BaseRenderer* sender, int type, int button, int buttonState, int key); */ WiiMoteButtonEvent(int type, int button, int buttonState, int key); ~WiiMoteButtonEvent(); //itk::EventObject implementation const char * GetEventName() const; bool CheckEvent(const ::itk::EventObject* e) const; ::itk::EventObject* MakeObject() const; protected: private: }; // end class } // end namespace mitk #endif // MITK_WIIMOTEBUTTONEVENT_H diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteCalibrationEvent.h b/Modules/InputDevices/WiiMote/mitkWiiMoteCalibrationEvent.h index 66884bff1d..d4d3c2e307 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteCalibrationEvent.h +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteCalibrationEvent.h @@ -1,66 +1,66 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITK_WIIMOTECALIBRATIONEVENT_H #define MITK_WIIMOTECALIBRATIONEVENT_H #include "mitkWiiMoteExports.h" #include "mitkEvent.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkInteractionConst.h" namespace mitk { class mitkWiiMote_EXPORT WiiMoteCalibrationEvent : public Event, itk::EventObject { public: typedef WiiMoteCalibrationEvent Self; typedef itk::EventObject Superclass; /** * Initializes a Wiimote Event, that stores additional information.
* Such as a the raw x and y coordinates of the IR input.
* * @param rawX * x coordinate of the IR sensor input * @param rawY * y coordinate of the IR sensor input */ WiiMoteCalibrationEvent(double rawX, double rawY); ~WiiMoteCalibrationEvent(); double GetXCoordinate() const; double GetYCoordinate() const; //itk::EventObject implementation const char * GetEventName() const; bool CheckEvent(const ::itk::EventObject* e) const; ::itk::EventObject* MakeObject() const; protected: private: double m_RawX; double m_RawY; }; } #endif // MITK_WIIMOTECALIBRATIONEVENT_H diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteIREvent.h b/Modules/InputDevices/WiiMote/mitkWiiMoteIREvent.h index b3d7903c5a..5ba51774d1 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteIREvent.h +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteIREvent.h @@ -1,75 +1,75 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITK_WIIMOTEIREVENT_H #define MITK_WIIMOTEIREVENT_H #include "mitkEvent.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkInteractionConst.h" #include "mitkWiiMoteExports.h" namespace mitk { /** * This event type is used for IR events triggered by the
* the Wiimote driver. */ class mitkWiiMote_EXPORT WiiMoteIREvent : public Event, itk::EventObject { public: typedef WiiMoteIREvent Self; typedef itk::EventObject Superclass; /** * Initializes a Wiimote Event, that stores additional information.
* Such as a vector and the time of the recording
* * @param inputData * the movement of the IR sensor computed in a vector * @param recordTime * the time at which the data was recorded */ WiiMoteIREvent( mitk::Vector2D inputData , double recordTime , int sliceNavigationValue); ~WiiMoteIREvent(); /** * Returns the current movement vector with the coordinates
* in the following order: x, y, z */ mitk::Vector2D GetMovementVector() const; double GetRecordTime() const; int GetSliceNavigationValue() const; //itk::EventObject implementation const char * GetEventName() const; bool CheckEvent(const ::itk::EventObject* e) const; ::itk::EventObject* MakeObject() const; private: mitk::Vector2D m_MovementVector; double m_RecordTime; int m_SliceNavigationValue; }; // end class } // end namespace mitk #endif // MITK_WIIMOTEIREVENT_H diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteInteractor.cpp b/Modules/InputDevices/WiiMote/mitkWiiMoteInteractor.cpp index e5919e6c21..fddf2b9e24 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteInteractor.cpp +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteInteractor.cpp @@ -1,776 +1,776 @@ /*=================================================================== 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 // mitk #include -#include +#include #include #include -#include +#include #include #include #include #include // vtk #include #include #include #include #include // vnl #include #include #define _USE_MATH_DEFINES // otherwise, constants will not work #include const double DELTATIME = 0.01; mitk::WiiMoteInteractor::WiiMoteInteractor(const char* type, DataNode* dataNode) : Interactor(type, dataNode) , m_OrientationX(0) , m_OrientationY(0) , m_OrientationZ(0) , m_xVelocity (0) , m_yVelocity (0) , m_zVelocity (0) , m_xAngle (0) , m_yAngle (0) , m_zAngle (0) , m_xValue (0) , m_yValue (0) , m_zValue (0) , m_InRotation(false) , m_TranslationMode(1) , m_OriginalGeometry(NULL) , m_SurfaceInteractionMode(1) { // save original geometry mitk::Geometry3D* temp = this->TransformCurrentDataInGeometry3D(); try { m_OriginalGeometry = dynamic_cast(temp->Clone().GetPointer()); } catch(...) { MITK_WARN << "Original geometry could not be stored!"; } // connect actions to methods CONNECT_ACTION(mitk::AcONWIIMOTEINPUT,OnWiiMoteInput); CONNECT_ACTION(mitk::AcONWIIMOTEBUTTONRELEASED,OnWiiMoteReleaseButton); CONNECT_ACTION(mitk::AcRESETVIEW,OnWiiMoteResetButton); } mitk::WiiMoteInteractor::~WiiMoteInteractor() { } bool mitk::WiiMoteInteractor::OnWiiMoteResetButton(Action* action, const mitk::StateEvent* stateEvent) { // resets the geometry, so that the // object will be returned to its // initial state try { mitk::Surface* surface = dynamic_cast(m_DataNode->GetData()); mitk::Geometry3D::Pointer temp = dynamic_cast(m_OriginalGeometry->Clone().GetPointer()); surface->SetGeometry(temp); if(surface == NULL) { MITK_WARN << "Original geometry could not be used for reset!"; } m_DataNode->SetData(surface); m_DataNode->Modified(); } catch(...) { MITK_ERROR << "Original geometry could not be retrieved"; } //reset the camera, so that the objects shown in the scene can be seen. const mitk::BaseRenderer* br = mitk::GlobalInteraction::GetInstance()->GetFocus(); const mitk::VtkPropRenderer* glRenderer = dynamic_cast(br); if (glRenderer) { vtkRenderer* vtkRenderer = glRenderer->GetVtkRenderer(); mitk::DataStorage* ds = br->GetDataStorage(); if (ds == NULL) return false; mitk::BoundingBox::Pointer bb = ds->ComputeBoundingBox(); mitk::Point3D middle = bb->GetCenter(); vtkRenderer->GetActiveCamera()->SetFocalPoint(middle[0],middle[1],middle[2]); vtkRenderer->ResetCamera(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return true; } return false; } bool mitk::WiiMoteInteractor::OnWiiMoteInput(Action* action, const mitk::StateEvent* stateEvent) { const mitk::WiiMoteAllDataEvent* wiiMoteEvent; try { wiiMoteEvent = dynamic_cast(stateEvent->GetEvent()); } catch(...) { MITK_ERROR << "Event is not wiimote event and could not be transformed\n"; } m_SurfaceInteractionMode = wiiMoteEvent->GetSurfaceInteractionMode(); //this->FixedRotationAndTranslation(wiiMoteEvent); // -------------------- values for translation -------------------- float xAccel = wiiMoteEvent->GetXAcceleration(); float yAccel = wiiMoteEvent->GetYAcceleration(); float zAccel = wiiMoteEvent->GetZAcceleration(); float pitch = wiiMoteEvent->GetPitch(); float roll = wiiMoteEvent->GetRoll(); m_OrientationX = wiiMoteEvent->GetOrientationX(); m_OrientationY = wiiMoteEvent->GetOrientationY(); m_OrientationZ = wiiMoteEvent->GetOrientationZ(); // substracts the proportionate force // applied by gravity depending on the // orientation float sinP = sin(pitch/180.0 * M_PI); float cosP = cos(pitch/180.0 * M_PI); float sinR = sin(roll/180.0 * M_PI); float cosR = cos(roll/180.0 * M_PI); // x acceleration if(m_OrientationZ >= 0) { m_xValue = xAccel - sinR * cosP; } else { m_xValue = xAccel + sinR * cosP; } //// against drift //if(std::abs(xAccel) < 0.2) //{ // m_xValue = 0; //} // y acceleration m_yValue = yAccel + sinP; //// against drift //if(std::abs(yAccel) < 0.2) //{ // m_yValue = 0; //} // z acceleration m_zValue = zAccel - cosP * cosR; //// against drift //if(std::abs(zAccel) < 0.3) //{ // m_zValue = 0; //} m_xVelocity += m_xValue; m_yVelocity += m_yValue; m_zVelocity -= m_zValue; // -------------------- values for rotation -------------------- ScalarType pitchSpeed = wiiMoteEvent->GetPitchSpeed(); ScalarType rollSpeed = wiiMoteEvent->GetRollSpeed(); ScalarType yawSpeed = wiiMoteEvent->GetYawSpeed(); // x angle if(std::abs(pitchSpeed) > 50 && std::abs(pitchSpeed) < 1000) { if(m_SurfaceInteractionMode == 1) { m_xAngle = (pitchSpeed * DELTATIME); } else { m_xAngle = (-pitchSpeed * DELTATIME); } } else { m_xAngle = 0; } // y angle if(std::abs(rollSpeed) > 50 && std::abs(rollSpeed) < 1000) { m_yAngle = (rollSpeed * DELTATIME); } else { m_yAngle = 0; } // z angle if(std::abs(yawSpeed) > 50 && std::abs(yawSpeed) < 1000) { if(m_SurfaceInteractionMode == 1) { m_zAngle = (yawSpeed * DELTATIME); } else { m_zAngle = (-yawSpeed * DELTATIME); } } else { m_zAngle = 0; } // -------------------- rotation and translation -------------------- bool result = false; result = this->DynamicRotationAndTranslation(this->TransformCurrentDataInGeometry3D()); return result; } bool mitk::WiiMoteInteractor::OnWiiMoteReleaseButton(Action* action, const mitk::StateEvent* stateEvent) { m_xVelocity = 0; m_yVelocity = 0; m_zVelocity = 0; m_xValue = 0; m_yValue = 0; m_zValue = 0; m_xAngle = 0; m_yAngle = 0; m_zAngle = 0; // only for fixed translation m_InRotation = false; m_TranslationMode = 1; return true; } mitk::Geometry3D* mitk::WiiMoteInteractor::TransformCurrentDataInGeometry3D() { //checking corresponding Data; has to be a surface or a subclass mitk::Surface* surface = dynamic_cast(m_DataNode->GetData()); if ( surface == NULL ) { MITK_WARN<<"Wiimote Interactor got wrong type of data! Aborting interaction!\n"; return NULL; } Geometry3D* geometry = surface->GetUpdatedTimeSlicedGeometry()->GetGeometry3D( m_TimeStep ); return geometry; } vnl_matrix_fixed mitk::WiiMoteInteractor::ComputeCurrentCameraPosition( vtkCamera* vtkCamera ) { vnl_matrix_fixed cameraMat; //first we need the position of the camera mitk::Vector3D camPosition; double camPositionTemp[3]; vtkCamera->GetPosition(camPositionTemp); camPosition[0] = camPositionTemp[0]; camPosition[1] = camPositionTemp[1]; camPosition[2] = camPositionTemp[2]; //then the upvector of the camera mitk::Vector3D upCamVector; double upCamTemp[3]; vtkCamera->GetViewUp(upCamTemp); upCamVector[0] = upCamTemp[0]; upCamVector[1] = upCamTemp[1]; upCamVector[2] = upCamTemp[2]; upCamVector.Normalize(); //then the vector to which the camera is heading at (focalpoint) mitk::Vector3D focalPoint; double focalPointTemp[3]; vtkCamera->GetFocalPoint(focalPointTemp); focalPoint[0] = focalPointTemp[0]; focalPoint[1] = focalPointTemp[1]; focalPoint[2] = focalPointTemp[2]; mitk::Vector3D focalVector; focalVector = focalPoint - camPosition; focalVector.Normalize(); //orthogonal vector to focalVector and upCamVector mitk::Vector3D crossVector; crossVector = CrossProduct(upCamVector, focalVector); crossVector.Normalize(); cameraMat.put(0,0,crossVector[0]); cameraMat.put(1,0,crossVector[1]); cameraMat.put(2,0,crossVector[2]); cameraMat.put(3,0,0); cameraMat.put(0,1,focalVector[0]); cameraMat.put(1,1,focalVector[1]); cameraMat.put(2,1,focalVector[2]); cameraMat.put(3,1,0); cameraMat.put(0,2,upCamVector[0]); cameraMat.put(1,2,upCamVector[1]); cameraMat.put(2,2,upCamVector[2]); cameraMat.put(3,2,0); cameraMat.put(0,3,camPosition[0]); cameraMat.put(1,3,camPosition[1]); cameraMat.put(2,3,camPosition[2]); cameraMat.put(3,3,1); return cameraMat; } bool mitk::WiiMoteInteractor::DynamicRotationAndTranslation(Geometry3D* geometry) { // computation of the delta transformation if(m_SurfaceInteractionMode == 1) { // necessary because the wiimote has // a different orientation when loaded // as an object file ScalarType temp = m_yAngle; m_yAngle = m_zAngle; m_zAngle = temp; } //vnl_quaternion Rx(m_OrientationX // ,m_OrientationY // ,m_OrientationZ // , m_xAngle); //vnl_quaternion Ry(Rx.axis()[0] // , Rx.axis()[1] // , Rx.axis()[2] // , m_yAngle); //vnl_quaternion Rz(Ry.axis()[0] // , Ry.axis()[1] // , Ry.axis()[2] // , m_zAngle); vnl_quaternion q( vtkMath::RadiansFromDegrees( m_xAngle ), vtkMath::RadiansFromDegrees( m_yAngle ), vtkMath::RadiansFromDegrees( m_zAngle ) ); //q = Rz * Ry * Rx; //q.normalize(); vnl_matrix_fixed deltaTransformMat = q.rotation_matrix_transpose_4(); // fill translation column deltaTransformMat(0,3) = m_xVelocity; deltaTransformMat(1,3) = m_yVelocity; deltaTransformMat(2,3) = m_zVelocity; // invert matrix to apply // correct order for the transformation deltaTransformMat = vnl_inverse(deltaTransformMat); vtkMatrix4x4* deltaTransform = vtkMatrix4x4::New(); // copy into matrix for(size_t i=0; i<4; ++i) for(size_t j=0; j<4; ++j) deltaTransform->SetElement(i,j, deltaTransformMat(i,j)); vtkMatrix4x4* objectTransform = vtkMatrix4x4::New(); if(m_SurfaceInteractionMode == 2) { // additional computation for transformation // relative to the camera view // get renderer const RenderingManager::RenderWindowVector& renderWindows = RenderingManager::GetInstance()->GetAllRegisteredRenderWindows(); for ( RenderingManager::RenderWindowVector::const_iterator iter = renderWindows.begin(); iter != renderWindows.end(); ++iter ) { if ( mitk::BaseRenderer::GetInstance((*iter))->GetMapperID() == BaseRenderer::Standard3D ) { m_BaseRenderer = mitk::BaseRenderer::GetInstance((*iter)); } } vtkCamera* camera = m_BaseRenderer->GetVtkRenderer()->GetActiveCamera(); //vtkMatrix4x4* cameraMat = vtkMatrix4x4::New(); vnl_matrix_fixed cameraMat; vnl_matrix_fixed objectMat; // copy object matrix for(size_t i=0; i<4; ++i) for(size_t j=0; j<4; ++j) objectMat.put(i,j, geometry->GetVtkTransform()->GetMatrix()->GetElement(i,j)); cameraMat = this->ComputeCurrentCameraPosition(camera); vnl_matrix_fixed newObjectMat; vnl_matrix_fixed objectToCameraMat; objectToCameraMat = vnl_inverse(cameraMat) * objectMat; newObjectMat = vnl_inverse(objectToCameraMat) * deltaTransformMat * objectToCameraMat * vnl_inverse(objectMat); newObjectMat = vnl_inverse(newObjectMat); newObjectMat.put(0,3,objectMat(0,3)+deltaTransformMat(0,3)); newObjectMat.put(1,3,objectMat(1,3)+deltaTransformMat(1,3)); newObjectMat.put(2,3,objectMat(2,3)+deltaTransformMat(2,3)); // copy result for(size_t i=0; i<4; ++i) for(size_t j=0; j<4; ++j) objectTransform->SetElement(i,j, newObjectMat(i,j)); } //copy m_vtkMatrix to m_VtkIndexToWorldTransform geometry->TransferItkToVtkTransform(); vtkTransform* vtkTransform = vtkTransform::New(); if(m_SurfaceInteractionMode == 1) { //m_VtkIndexToWorldTransform as vtkLinearTransform* vtkTransform->SetMatrix( geometry->GetVtkTransform()->GetMatrix() ); vtkTransform->Concatenate( deltaTransform ); geometry->SetIndexToWorldTransformByVtkMatrix( vtkTransform->GetMatrix() ); } else { geometry->SetIndexToWorldTransformByVtkMatrix( objectTransform ); } geometry->Modified(); m_DataNode->Modified(); vtkTransform->Delete(); objectTransform->Delete(); deltaTransform->Delete(); //update rendering mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return true; } bool mitk::WiiMoteInteractor::FixedRotationAndTranslation(const mitk::WiiMoteAllDataEvent* wiiMoteEvent) { Geometry3D* geometry = this->TransformCurrentDataInGeometry3D(); m_OrientationX = wiiMoteEvent->GetOrientationX(); m_OrientationY = wiiMoteEvent->GetOrientationY(); m_OrientationZ = wiiMoteEvent->GetOrientationZ(); ScalarType pitchSpeed = wiiMoteEvent->GetPitchSpeed(); ScalarType rollSpeed = wiiMoteEvent->GetRollSpeed(); ScalarType yawSpeed = wiiMoteEvent->GetYawSpeed(); // angle x if(std::abs(pitchSpeed) < 200) pitchSpeed = 0; m_xAngle += (pitchSpeed / 1500); // angle y if(std::abs(rollSpeed) < 200) rollSpeed = 0; m_yAngle += (rollSpeed / 1500); // angle z if(std::abs(yawSpeed) < 200) yawSpeed = 0; m_zAngle += (yawSpeed / 1500); if( std::abs(pitchSpeed) > 200 || std::abs(rollSpeed) > 200 || std::abs(yawSpeed) > 200) { m_InRotation = true; //// depending on a combination of the //// orientation the angleX wil be altered //// because the range from roll is limited - //// range: -90° to 90° by the wiimote + //// range: -90� to 90� by the wiimote //if(wiiMoteEvent->GetOrientationZ() < 0) //{ // // value is positive // if(wiiMoteEvent->GetOrientationX() > 0) // { // // the degree measured decreases after it reaches // // in the "real" world the 90 degree angle // // (rotation to the right side) // // therefore it needs to artificially increased // // measured value drops -> computated angle increases // angleX = 90 - angleX; // // now add the "new" angle to 90 degree threshold // angleX += 90; // } // // value is negative // else if(wiiMoteEvent->GetOrientationX() < 0) // { // // the degree measured increases after it reaches // // in the "real" world -90 degree // // (rotation to the left side) // // therefore it needs to be artificially decreased // // (example -90 -> -70, but -110 is needed) // // measured value increases -> computated angle decreases // angleX = 90 + angleX; // // invert the algebraic sign, because it is the "negative" // // side of the rotation // angleX = -angleX; // // now add the negative value to the -90 degree threshold // // to decrease the value further // angleX -= 90; // } // else if(wiiMoteEvent->GetOrientationX() == 0) // { // // i.e. wiimote is flipped upside down // angleX = 180; // } //} //rotation vtkTransform *vtkTransform = vtkTransform::New(); //copy m_vtkMatrix to m_VtkIndexToWorldTransform geometry->TransferItkToVtkTransform(); //////m_VtkIndexToWorldTransform as vtkLinearTransform* vtkTransform->SetMatrix(geometry->GetVtkTransform()->GetMatrix()); // rotation from center is different // from rotation while translated // hence one needs the center of the object Point3D center = geometry->GetOrigin(); vtkTransform->PostMultiply(); vtkTransform->Translate(-center[0], -center[1], -center[2]); //vtkTransform->RotateWXYZ(angle, rotationVector[0], rotationVector[1], rotationVector[2]); vtkTransform->RotateX(m_xAngle); vtkTransform->RotateY(m_zAngle); vtkTransform->RotateZ(m_yAngle); vtkTransform->Translate(center[0], center[1], center[2]); vtkTransform->PreMultiply(); geometry->SetIndexToWorldTransformByVtkMatrix(vtkTransform->GetMatrix()); geometry->Modified(); // indicate modification of data tree node m_DataNode->Modified(); vtkTransform->Delete(); //update rendering mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return true; } else if(!m_InRotation) { float xValue = wiiMoteEvent->GetXAcceleration(); float yValue = wiiMoteEvent->GetYAcceleration(); float zValue = wiiMoteEvent->GetZAcceleration(); float pitch = wiiMoteEvent->GetPitch(); float roll = wiiMoteEvent->GetRoll(); // substracts the proportionate force // applied by gravity depending on the // orientation float sinP = sin(pitch/180.0 * M_PI); float cosP = cos(pitch/180.0 * M_PI); float sinR = sin(roll/180.0 * M_PI); float cosR = cos(roll/180.0 * M_PI); // x acceleration if(m_OrientationZ >= 0) xValue = xValue - sinR * cosP; else xValue = xValue + sinR * cosP; // against drift if(std::abs(xValue) < 0.2) xValue = 0; // y acceleration yValue = yValue + sinP; // against drift if(std::abs(yValue) < 0.2) yValue = 0; // z acceleration zValue = zValue - cosP * cosR; // against drift if(std::abs(zValue) < 0.3) zValue = 0; // simple integration over time // resulting in velocity switch(m_TranslationMode) { case 1: m_xVelocity -= xValue; m_yVelocity -= yValue; m_zVelocity += zValue; // 1 = movement to the right // initially starts with negative acceleration // 2 = movement to the left // initially starts with positive acceleration if( m_xVelocity > 0 && xValue > 0 // 1 || m_xVelocity < 0 && xValue < 0) // 2 { m_xVelocity += xValue; } else if( m_xVelocity > 0 && xValue < 0 // 1 || m_xVelocity < 0 && xValue > 0) // 2 { m_xVelocity -= xValue; } break; case 3: m_yVelocity -= yValue; break; case 4: // 1 = movement up // initially starts with positive acceleration // 2 = movement down // initially starts with negative acceleration if( m_zVelocity > 0 && zValue < 0 // 1 || m_zVelocity < 0 && zValue > 0) // 2 { m_zVelocity -= zValue; } else if(m_zVelocity > 0 && zValue > 0 // 1 || m_zVelocity < 0 && zValue < 0) // 2 { m_zVelocity += zValue; } break; } // sets the mode of the translation // depending on the initial velocity if( std::abs(m_xVelocity) > std::abs(m_yVelocity) && std::abs(m_xVelocity) > std::abs(m_zVelocity) ) { m_TranslationMode = 2; m_yVelocity = 0; m_zVelocity = 0; } else if( std::abs(m_yVelocity) > std::abs(m_xVelocity) && std::abs(m_yVelocity) > std::abs(m_zVelocity) ) { m_TranslationMode = 3; m_xVelocity = 0; m_zVelocity = 0; } else if(std::abs(m_zVelocity) > std::abs(m_xVelocity) && std::abs(m_zVelocity) > std::abs(m_yVelocity) ) { m_TranslationMode = 4; m_xVelocity = 0; m_yVelocity = 0; } // translation mitk::Vector3D movementVector; movementVector.SetElement(0,m_xVelocity); movementVector.SetElement(1,m_yVelocity); movementVector.SetElement(2,m_zVelocity); geometry->Translate(movementVector); // indicate modification of data tree node m_DataNode->Modified(); // update rendering mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return true; } return false; } diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteMultiIREvent.h b/Modules/InputDevices/WiiMote/mitkWiiMoteMultiIREvent.h index fb415f0758..0690bde941 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteMultiIREvent.h +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteMultiIREvent.h @@ -1,53 +1,53 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITK_WIIMOTEMULTIIREVENT_H #define MITK_WIIMOTEMULITIREVENT_H #include "mitkInputDevicesExports.h" #include "mitkEvent.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkInteractionConst.h" namespace mitk { class mitkInputDevices_EXPORT WiiMoteMultiIREvent : public Event, itk::EventObject { public: typedef WiiMoteMultiIREvent Self; typedef itk::EventObject Superclass; WiiMoteMultiIREvent(mitk::Point3D Coordinate3D); ~WiiMoteMultiIREvent(); mitk::Point3D Get3DCoordinate() const; //itk::EventObject implementation const char * GetEventName() const; bool CheckEvent(const ::itk::EventObject* e) const; ::itk::EventObject* MakeObject() const; protected: private: mitk::Point3D m_3DCoordinate; }; // end class } // end namspace #endif // MITK_WIIMOTEMULITIREVENT_H diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteThread.h b/Modules/InputDevices/WiiMote/mitkWiiMoteThread.h index 696471a70d..78f6841929 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteThread.h +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteThread.h @@ -1,218 +1,218 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITK_WIIMOTEHTREAD_H #define MITK_WIIMOTEHTREAD_H #include "wiimote.h" // mitk #include "mitkCommon.h" #include "mitkCallbackFromGUIThread.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkKalmanFilter.h" // itk #include "itkObject.h" #include "itkMultiThreader.h" #include "itkFastMutexLock.h" #include "itksys/SystemTools.hxx" // used for GetTime() and Delay(); namespace mitk { // instead of include, enables this class to know the addon class WiiMoteAddOn; class WiiMoteThread : public itk::Object { public: // typedefs are used in context with CallbackFromGUIThread typedef itk::ReceptorMemberCommand ReceptorCommand; // eventually probs with Linux -> typename typedef ReceptorCommand::Pointer ReceptorCommandPointer; WiiMoteThread(); ~WiiMoteThread(); /** * Allows to set report types, detects extensions and responds to connect/disconnect
* events of extension, such as MotionPlus. * * NOTE: don't access the public state from the 'remote' object here, as it will * be out-of-date (it's only updated via RefreshState() calls, and these * are reserved for the main application so it can be sure the values * stay consistent between calls). Instead query 'new_state' only. * * @param remote * the old state of the connected Wii remote * @param changed * the state change of the Wii remote * @param newState * the new state, after the change is applied (i.e. new extension connected) * */ static void OnStateChange(wiimote &remote, state_change_flags changed, const wiimote_state &newState); /** * Starts the thread for the Wiimote. */ void Run(); /** * Helper function, because the itk::MultiThreader can only
* start a new thread with a static member function. */ static ITK_THREAD_RETURN_TYPE StartWiiMoteThread(void* data); /** * Connects the Wiimote and allows access to its functionality. */ void StartWiiMote(); /** * Stops the running thread. */ void StopWiiMote(); /** * Reconnects the Wiimote in case the connection is lost. */ void ReconnectWiiMote(); /** * Detects all available Wiimotes. * * TODO: more detailed regarding the mode and led lighting */ bool DetectWiiMotes(); /** * Disconnects all connected Wiimotes. */ void DisconnectWiiMotes(); /** * Reads incoming data from the IR camera. After processing the data
* (e.g. computations, assigning commands...) fires Wiimote events accordingly. * */ void WiiMoteIRInput(); /** * Reads incoming data from buttons. After processing the data
* (e.g. computations, assigning commands...) fires Wiimote events
* that indicate a button was pressed. * * @param buttonType * the type of button, that was used to trigger this event */ void WiiMoteButtonPressed(int buttonType); /** * Reads incoming data from buttons. After processing the data
* (e.g. computations, assigning commands...) fires Wiimote events
* that indicate a button release. * * @param buttonType * the type of button, that was used to trigger this event */ void WiiMoteButtonReleased(int buttonType); /** * Reads incoming data from the IR camera. Afterwards the raw x and y coordinates
* are stored in an event and fired as an event. * */ void WiiMoteCalibrationInput(); /** * Constantly refreshes the state of a single wiimote. Also changes between
* the calibration mode and the IR input mode through button push. * * TODO: more detailed explanation of calibration * */ void SingleWiiMoteUpdate(); /** * Constantly refreshes the state of multiple wiimotes. */ void MultiWiiMoteUpdate(); /** * Processes the different IR inputs from multiple wiimotes. */ void MultiWiiMoteIRInput(); /** * Sets the modus for the first connected Wiimote depending
* on the given parameter. * * @param activated * true, the Surface Interaction modus will be activated * false, the Surface Interaction modus will be deactivated */ void SetWiiMoteSurfaceIModus(bool activated); // TODO void SurfaceInteraction(); protected: private: // threading int m_ThreadID; itk::MultiThreader::Pointer m_MultiThreader; // mutex to control the flow of the method StartWiiMote() itk::FastMutexLock::Pointer m_WiiMoteThreadFinished; bool m_StopWiiMote; // access to the wiimote and parameter for callbackfromguithread ReceptorCommandPointer m_Command; // required for computation of movement Point2D m_LastReadData; double m_LastRecordTime; bool m_ReadDataOnce; // modes bool m_InCalibrationMode; bool m_SurfaceInteraction; bool m_ButtonBPressed; // Default: 1 = relative to object // 2 = relative to camera view int m_SurfaceInteractionMode; //store all connected Wiimotes wiimote m_WiiMotes[4]; int m_NumberDetectedWiiMotes; // used for measuring movement int m_TimeStep; // Kalman filter mitk::KalmanFilter::Pointer m_Kalman; }; } #endif // MITK_WIIMOTEHTREAD_H diff --git a/Modules/IpPicSupport/mitkPicHelper.h b/Modules/IpPicSupport/mitkPicHelper.h index f4cc3baa7f..f41d0ae8b8 100644 --- a/Modules/IpPicSupport/mitkPicHelper.h +++ b/Modules/IpPicSupport/mitkPicHelper.h @@ -1,52 +1,52 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKPICHELPER_H_HEADER_INCLUDED_C1F4DAB4 #define MITKPICHELPER_H_HEADER_INCLUDED_C1F4DAB4 #include -#include "mitkVector.h" +#include "mitkTypes.h" #include namespace mitk { class SlicedGeometry3D; //##Documentation //## @brief Internal class for managing references on sub-images //## @ingroup Data class IpPicSupport_EXPORT PicHelper { public: static const char *GetNameOfClass() { return "PicHelper"; } static bool GetSpacing(const mitkIpPicDescriptor* pic, Vector3D & spacing); static bool SetSpacing(const mitkIpPicDescriptor* pic, SlicedGeometry3D* slicedgeometry); static bool GetTimeSpacing(const mitkIpPicDescriptor* pic, float& timeSpacing); static void InitializeEvenlySpaced(const mitkIpPicDescriptor* pic, unsigned int slices, SlicedGeometry3D* slicedgeometry); static bool SetGeometry2D(const mitkIpPicDescriptor* pic, int s, SlicedGeometry3D* slicedgeometry); }; } // namespace mitk #endif /* MITKPICHELPER_H_HEADER_INCLUDED_C1F4DAB4 */ diff --git a/Modules/MitkExt/Algorithms/mitkAngleCorrectByPointFilter.h b/Modules/MitkExt/Algorithms/mitkAngleCorrectByPointFilter.h index 68516a4183..efba613da8 100644 --- a/Modules/MitkExt/Algorithms/mitkAngleCorrectByPointFilter.h +++ b/Modules/MitkExt/Algorithms/mitkAngleCorrectByPointFilter.h @@ -1,74 +1,74 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKANGLECORRECTBYPOINTFILTER_H_HEADER_INCLUDED_C1F48A22 #define MITKANGLECORRECTBYPOINTFILTER_H_HEADER_INCLUDED_C1F48A22 #include "mitkCommon.h" #include "MitkExtExports.h" #include "mitkImageToImageFilter.h" -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { //##Documentation //## @brief //## @ingroup Process class MitkExt_EXPORT AngleCorrectByPointFilter : public ImageToImageFilter { public: mitkClassMacro(AngleCorrectByPointFilter, ImageToImageFilter); itkNewMacro(Self); itkSetMacro(Center, Point3D); itkGetConstReferenceMacro(Center, Point3D); itkSetMacro(TransducerPosition, Point3D); itkGetConstReferenceMacro(TransducerPosition, Point3D); itkSetMacro(PreferTransducerPositionFromProperty, bool); itkGetMacro(PreferTransducerPositionFromProperty, bool); protected: //##Description //## @brief Time when Header was last initialized itk::TimeStamp m_TimeOfHeaderInitialization; protected: AngleCorrectByPointFilter(); ~AngleCorrectByPointFilter(); virtual void GenerateData(); virtual void GenerateOutputInformation(); virtual void GenerateInputRequestedRegion(); Point3D m_TransducerPosition; Point3D m_Center; bool m_PreferTransducerPositionFromProperty; }; } // namespace mitk #endif /* MITKANGLECORRECTBYPOINTFILTER_H_HEADER_INCLUDED_C1F48A22 */ diff --git a/Modules/MitkExt/Controllers/mitkMultiStepper.h b/Modules/MitkExt/Controllers/mitkMultiStepper.h index 60654ebe50..853ccad15f 100644 --- a/Modules/MitkExt/Controllers/mitkMultiStepper.h +++ b/Modules/MitkExt/Controllers/mitkMultiStepper.h @@ -1,68 +1,68 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MULTISTEPPER_H_HEADER_INCLUDED #define MULTISTEPPER_H_HEADER_INCLUDED #include #include "MitkExtExports.h" #include "mitkCommon.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkStepper.h" #include #include namespace mitk { //##Documentation //## @brief Helper class to step through a list //## //## A helper class to step through a list. Does not contain the list, just the //## position in the list (between 0 and GetSteps()). Provides methods like //## First (go to the first element), Next (go to the next one), etc. //## @ingroup NavigationControl class MitkExt_EXPORT MultiStepper : public Stepper { public: mitkClassMacro(MultiStepper, Stepper); itkNewMacro(Self); void AddStepper(Stepper::Pointer stepper,unsigned int repeat = 1); void RemoveStepper(Stepper::Pointer stepper,unsigned int repeat = 1); /*void Next(); void Previous(); void First(); void Last(); */ // unsigned int GetPos(); void SetPos(unsigned int pos); void SetSteps(const unsigned int steps); protected: MultiStepper(); virtual ~MultiStepper(); typedef std::set StepperSet; typedef std::map ScaleFactorMap; StepperSet m_SubSteppers; ScaleFactorMap m_ScaleFactors; Stepper::Pointer m_LargestRangeStepper; void UpdateStepCount(); }; } // namespace mitk #endif /* MULTISTEPPER_H_HEADER_INCLUDED */ diff --git a/Modules/MitkExt/Controllers/mitkTDMouseVtkCameraController.cpp b/Modules/MitkExt/Controllers/mitkTDMouseVtkCameraController.cpp index 92135bac60..fc8f759938 100644 --- a/Modules/MitkExt/Controllers/mitkTDMouseVtkCameraController.cpp +++ b/Modules/MitkExt/Controllers/mitkTDMouseVtkCameraController.cpp @@ -1,241 +1,241 @@ /*=================================================================== 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 "mitkTDMouseVtkCameraController.h" #include "mitkVtkPropRenderer.h" #include "vtkCamera.h" #include "vtkRenderer.h" #include "vtkTransform.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkInteractionConst.h" #include "mitkStateEvent.h" #include "mitkTDMouseEventThrower.h" #include "mitkTDMouseEvent.h" #include "mitkGlobalInteraction.h" #include "vtkMath.h" const double TRANSLATIONSENSITIVITY = 2.0; const double ROTATIONSENSIVITY = 3.5; const double ANGLESENSITIVITY = 3.5; mitk::TDMouseVtkCameraController::TDMouseVtkCameraController() : CameraController("TDMouseInteraction") { //activate and instanciate EventThrower mitk::TDMouseEventThrower* thrower = mitk::TDMouseEventThrower::GetInstance(); //add this to GlobalInteracion to listen to events mitk::GlobalInteraction::GetInstance()->AddListener(this); //connect method this->OnTDMouseEvent to StateMachineEventMechanism CONNECT_ACTION(AcONTDMOUSEINPUT, OnTDMouseEvent); CONNECT_ACTION(AcONTDMOUSEKEYDOWN, OnTDMouseKeyDown); m_ClippingRangeIsSet = false; } mitk::TDMouseVtkCameraController::~TDMouseVtkCameraController() { } bool mitk::TDMouseVtkCameraController::OnTDMouseEvent(mitk::Action* a, const mitk::StateEvent* e) { //only if 3D rendering mitk::BaseRenderer const* br = this->GetRenderer(); mitk::BaseRenderer::MapperSlotId id = ((mitk::BaseRenderer*)(br))->GetMapperID(); if (id != mitk::BaseRenderer::Standard3D) return true; //only if focused by the FocusManager if (this->GetRenderer() != mitk::GlobalInteraction::GetInstance()->GetFocus()) return true; //pre-checking for safety vtkRenderer* vtkRenderer = ((mitk::VtkPropRenderer*)this->GetRenderer())->GetVtkRenderer(); if (vtkRenderer == NULL) return false; vtkCamera* vtkCam = (vtkCamera*)vtkRenderer->GetActiveCamera(); if(!m_ClippingRangeIsSet) vtkCam->SetClippingRange(0.1, 1000000); const mitk::TDMouseEvent* tdevent = dynamic_cast(e->GetEvent()); if (tdevent == NULL) { std::cout<<"Wrong event for TDMouseCameraController!"<GetTranslation(); mitk::Vector3D rotation = tdevent->GetRotation(); mitk::ScalarType angle = tdevent->GetAngle(); //output for debug //std::cout<<"translation: "<GetDataStorage(); mitk::BoundingBox::Pointer bb = ds->ComputeBoundingBox(); mitk::BoundingBox::AccumulateType length = bb->GetDiagonalLength2(); if (length > 0.00001)//if length not zero sceneSensivity *= 100.0 / (sqrt(length)) ; //sensivity to adapt to mitk speed translation *= sceneSensivity * TRANSLATIONSENSITIVITY; rotation *= sceneSensivity * ROTATIONSENSIVITY; angle *= sceneSensivity * ANGLESENSITIVITY; //compute the global space coordinates from the relative mouse coordinate //first we need the position of the camera mitk::Vector3D camPosition; double camPositionTemp[3]; vtkCam->GetPosition(camPositionTemp); camPosition[0] = camPositionTemp[0]; camPosition[1] = camPositionTemp[1]; camPosition[2] = camPositionTemp[2]; //then the upvector of the camera mitk::Vector3D upCamVector; double upCamTemp[3]; vtkCam->GetViewUp(upCamTemp); upCamVector[0] = upCamTemp[0]; upCamVector[1] = upCamTemp[1]; upCamVector[2] = upCamTemp[2]; upCamVector.Normalize(); //then the vector to which the camera is heading at (focalpoint) mitk::Vector3D focalPoint; double focalPointTemp[3]; vtkCam->GetFocalPoint(focalPointTemp); focalPoint[0] = focalPointTemp[0]; focalPoint[1] = focalPointTemp[1]; focalPoint[2] = focalPointTemp[2]; mitk::Vector3D focalVector; focalVector = focalPoint - camPosition; focalVector.Normalize(); //orthogonal vector to focalVector and upCamVector mitk::Vector3D crossVector; crossVector = CrossProduct(upCamVector, focalVector); crossVector.Normalize(); //now we have the current orientation so we can adapt it according to the current information, which we got from the TDMouse //new position of the camera: //left/right = camPosition + crossVector * translation[0]; mitk::Vector3D vectorX = crossVector * -translation[0]; //changes the magnitude, not the direction double nextCamPosition[3]; nextCamPosition[0] = camPosition[0] + vectorX[0]; nextCamPosition[1] = camPosition[1] + vectorX[1]; nextCamPosition[2] = camPosition[2] + vectorX[2]; //now the up/down movement mitk::Vector3D vectorY = upCamVector * translation[1]; //changes the magnitude, not the direction nextCamPosition[0] += vectorY[0]; nextCamPosition[1] += vectorY[1]; nextCamPosition[2] += vectorY[2]; //forward/backward movement mitk::Vector3D vectorZ = focalVector * -translation[2]; //changes the magnitude, not the direction nextCamPosition[0] += vectorZ[0]; nextCamPosition[1] += vectorZ[1]; nextCamPosition[2] += vectorZ[2]; //set the next position double nextPosition[3]; nextPosition[0] = nextCamPosition[0]; nextPosition[1] = nextCamPosition[1]; nextPosition[2] = nextCamPosition[2]; vtkCam->SetPosition(nextPosition); //adapt the focal point the same way double currentFocalPoint[3], nextFocalPoint[3]; vtkCam->GetFocalPoint(currentFocalPoint); nextFocalPoint[0] = currentFocalPoint[0] + vectorX[0] + vectorY[0] + vectorZ[0]; nextFocalPoint[1] = currentFocalPoint[1] + vectorX[1] + vectorY[1] + vectorZ[1]; ; nextFocalPoint[2] = currentFocalPoint[2] + vectorX[2] + vectorY[2] + vectorZ[2]; vtkCam->SetFocalPoint(nextFocalPoint); //now adapt the rotation of the mouse and adapt the camera according to it //Pitch: //Rotate the focal point about the cross product of the view up vector and the direction of //projection, centered at the camera's position. vtkCam->Pitch(rotation[0]*angle); //Yaw: //Rotate the focal point about the view up vector centered at the camera's position. //Note that the view up vector is not necessarily perpendicular to the direction of projection. vtkCam->Yaw(rotation[1]*angle); //Roll: //Rotate the camera about the direction of projection. vtkCam->Roll(-rotation[2]*angle * 1.5);//*1.5 to speed up the rotation[2] a little bit //Recompute the ViewUp vector to force it to be perpendicular to camera->focalpoint vector. //Unless you are going to use Yaw or Azimuth on the camera, there is no need to do this. vtkCam->OrthogonalizeViewUp(); //no zooming, only translating to the front or back // dolly: Move the position of the camera along the direction // of projection. Moving towards the focal point (e.g., greater // than 1) is a dolly-in, moving away from the focal point // (e.g., less than 1) is a dolly-out. //double distance = ((tdevent->GetTranslation())[1] / 10.0);//make it less sensitive in comparison to translation and rotatipn //vtkCam->Dolly(1.0 + distance ); //Reset the camera clipping range based on the bounds of the visible actors. //This ensures that no props are cut off vtkRenderer->ResetCameraClippingRange(); mitk::RenderingManager::GetInstance()->ForceImmediateUpdate(mitk::GlobalInteraction::GetInstance()->GetFocus()->GetRenderWindow()); return true; } bool mitk::TDMouseVtkCameraController::OnTDMouseKeyDown(mitk::Action* a, const mitk::StateEvent* e) { //reset the camera, so that the objects shown in the scene can be seen. const mitk::VtkPropRenderer* glRenderer = dynamic_cast(m_Renderer); if (glRenderer) { vtkRenderer* vtkRenderer = glRenderer->GetVtkRenderer(); mitk::DataStorage* ds = m_Renderer->GetDataStorage(); if (ds == NULL) return false; mitk::BoundingBox::Pointer bb = ds->ComputeBoundingBox(); mitk::Point3D middle =bb->GetCenter(); vtkRenderer->GetActiveCamera()->SetFocalPoint(middle[0],middle[1],middle[2]); vtkRenderer->ResetCamera(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return true; } return false; } diff --git a/Modules/MitkExt/DataManagement/mitkAffineTransformationOperation.h b/Modules/MitkExt/DataManagement/mitkAffineTransformationOperation.h index 95d87a795d..17f753605c 100644 --- a/Modules/MitkExt/DataManagement/mitkAffineTransformationOperation.h +++ b/Modules/MitkExt/DataManagement/mitkAffineTransformationOperation.h @@ -1,45 +1,45 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKAFFINETRANSFORMATIONOPERATION_H_HEADER_INCLUDED #define MITKAFFINETRANSFORMATIONOPERATION_H_HEADER_INCLUDED #include "mitkPointOperation.h" #include "MitkExtExports.h" -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { //##Documentation //## @brief Operation, that holds everything necessary for an affine operation. //## //## @ingroup Undo class MitkExt_EXPORT AffineTransformationOperation : public PointOperation { public: AffineTransformationOperation(OperationType operationType, Point3D point, ScalarType angle, int index); virtual ~AffineTransformationOperation(void); ScalarType GetAngle(); protected: ScalarType m_Angle; }; } // namespace mitk #endif /* MITKAFFINETRANSFORMATIONOPERATION_H_HEADER_INCLUDED */ diff --git a/Modules/MitkExt/DataManagement/mitkCellOperation.h b/Modules/MitkExt/DataManagement/mitkCellOperation.h index 81b671a809..3266468607 100644 --- a/Modules/MitkExt/DataManagement/mitkCellOperation.h +++ b/Modules/MitkExt/DataManagement/mitkCellOperation.h @@ -1,56 +1,56 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKCELLOPERATION_H_INCLUDED #define MITKCELLOPERATION_H_INCLUDED #include "mitkCommon.h" #include "MitkExtExports.h" #include "mitkOperation.h" -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { //##Documentation //## @brief Operation, that holds everything necessary for an operation on a cell. //## //## @ingroup Undo class MitkExt_EXPORT CellOperation : public Operation { public: mitkClassMacro(CellOperation, Operation); //##Documentation //##@brief constructor //## //## @param //## operationType is the type of that operation (see mitkOperation.h; e.g. move or add; Information for StateMachine::ExecuteOperation()); //## cellId: Id of the cell and a vector if needed CellOperation(OperationType operationType, int cellId, Vector3D vector); CellOperation(OperationType operationType, int cellId); virtual ~CellOperation(){}; int GetCellId() {return m_CellId;}; Vector3D GetVector() {return m_Vector;}; protected: int m_CellId; Vector3D m_Vector; }; }//namespace mitk #endif /* MITKCELLOPERATION_H_INCLUDED*/ diff --git a/Modules/MitkExt/DataManagement/mitkCone.cpp b/Modules/MitkExt/DataManagement/mitkCone.cpp index 68218175b7..e7e3f9219f 100644 --- a/Modules/MitkExt/DataManagement/mitkCone.cpp +++ b/Modules/MitkExt/DataManagement/mitkCone.cpp @@ -1,65 +1,65 @@ /*=================================================================== 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 "mitkCone.h" #include "vtkLinearTransform.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "vtkConeSource.h" mitk::Cone::Cone() : BoundingObject() { // Set up Cone Surface. Radius 1.0, height 2.0, , centered around the origin vtkConeSource* cone = vtkConeSource::New(); cone->SetRadius(1.0); cone->SetHeight(2.0); cone->SetDirection(0.0, -1.0, 0.0); cone->SetCenter(0.0, 0.0, 0.0); cone->SetResolution(20); cone->CappingOn(); cone->Update(); SetVtkPolyData(cone->GetOutput()); cone->Delete(); } mitk::Cone::~Cone() { } bool mitk::Cone::IsInside(const Point3D& worldPoint) const { // transform point from world to object coordinates ScalarType p[4]; p[0] = worldPoint[0]; p[1] = worldPoint[1]; p[2] = worldPoint[2]; p[3] = 1; GetGeometry()->GetVtkTransform()->GetInverse()->TransformPoint(p, p); p[1] += 1; // translate point, so that it fits to the formula below, which describes a cone that has its cone vertex at the origin return (sqrt(p[0] * p[0] + p[2] * p[2]) <= p[1] * 0.5) && (p[1] <= 2); // formula to calculate if a given point is inside a cone that has its cone vertex at the origin, is aligned on the second axis, has a radius of one an a height of two } mitk::ScalarType mitk::Cone::GetVolume() { Geometry3D* geometry = GetTimeSlicedGeometry(); return geometry->GetExtentInMM(0) * 0.5 * geometry->GetExtentInMM(2) * 0.5 * vnl_math::pi / 3.0 * geometry->GetExtentInMM(1); } diff --git a/Modules/MitkExt/DataManagement/mitkCuboid.cpp b/Modules/MitkExt/DataManagement/mitkCuboid.cpp index 2e569b9dca..2e28153214 100644 --- a/Modules/MitkExt/DataManagement/mitkCuboid.cpp +++ b/Modules/MitkExt/DataManagement/mitkCuboid.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 "mitkCuboid.h" #include "vtkLinearTransform.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "vtkCubeSource.h" #include mitk::Cuboid::Cuboid() : BoundingObject() { vtkCubeSource* cube = vtkCubeSource::New(); cube->SetXLength(2.0); cube->SetYLength(2.0); cube->SetZLength(2.0); cube->Update(); SetVtkPolyData(cube->GetOutput()); cube->Delete(); } mitk::Cuboid::~Cuboid() { } bool mitk::Cuboid::IsInside(const Point3D& worldPoint) const { // transform point from world to object coordinates ScalarType p[4]; p[0] = worldPoint[0]; p[1] = worldPoint[1]; p[2] = worldPoint[2]; p[3] = 1; GetGeometry()->GetVtkTransform()->GetInverse()->TransformPoint(p, p); return (p[0] >= -1) && (p[0] <= 1) && (p[1] >= -1) && (p[1] <= 1) && (p[2] >= -1) && (p[2] <= 1); } mitk::ScalarType mitk::Cuboid::GetVolume() { Geometry3D* geometry = GetTimeSlicedGeometry(); return geometry->GetExtentInMM(0) * geometry->GetExtentInMM(1) * geometry->GetExtentInMM(2); } diff --git a/Modules/MitkExt/DataManagement/mitkCylinder.cpp b/Modules/MitkExt/DataManagement/mitkCylinder.cpp index 4e32b17089..dd8fb460dc 100644 --- a/Modules/MitkExt/DataManagement/mitkCylinder.cpp +++ b/Modules/MitkExt/DataManagement/mitkCylinder.cpp @@ -1,68 +1,68 @@ /*=================================================================== 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 "mitkCylinder.h" #include "vtkLinearTransform.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "vtkCylinderSource.h" mitk::Cylinder::Cylinder() : BoundingObject() { vtkCylinderSource* cylinder = vtkCylinderSource::New(); cylinder->SetRadius(1.0); cylinder->SetHeight(2.0); cylinder->SetCenter(0.0, 0.0, 0.0); cylinder->SetResolution(100); cylinder->CappingOn(); cylinder->Update(); SetVtkPolyData(cylinder->GetOutput()); cylinder->Delete(); } mitk::Cylinder::~Cylinder() { } bool mitk::Cylinder::IsInside(const Point3D& worldPoint) const { // transform point from world to object coordinates ScalarType p[4]; p[0] = worldPoint[0]; p[1] = worldPoint[1]; p[2] = worldPoint[2]; p[3] = 1; GetGeometry()->GetVtkTransform()->GetInverse()->TransformPoint(p, p); mitk::ScalarType v = pow(p[0], 2) + pow(p[2], 2); bool retval = (v <= 1) && (p[1] >= -1) && (p[1] <= 1); return retval; } mitk::ScalarType mitk::Cylinder::GetVolume() { Geometry3D* geometry = GetTimeSlicedGeometry(); return geometry->GetExtentInMM(0) * 0.5 * geometry->GetExtentInMM(2) * 0.5 * vnl_math::pi * geometry->GetExtentInMM(1); } diff --git a/Modules/MitkExt/DataManagement/mitkDrawOperation.h b/Modules/MitkExt/DataManagement/mitkDrawOperation.h index 4eb8729be2..127fb5a573 100755 --- a/Modules/MitkExt/DataManagement/mitkDrawOperation.h +++ b/Modules/MitkExt/DataManagement/mitkDrawOperation.h @@ -1,76 +1,76 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKDRAWOPERATION_H #define MITKDRAWOPERATION_H #include #include "MitkExtExports.h" #include -#include +#include #include #include namespace mitk { //##Documentation //## @brief DrawOperation, that handles all actions on seeds. //## //## Stores everything for adding and deleting seeds. //## @ingroup Undo class MitkExt_EXPORT DrawOperation : public Operation { public: //##Documentation //##@brief DrawOperation, that handles all actions on seeds. //## //## @param operationType is the type of that operation (see mitkOperation.h; e.g. move or add; Information for StateMachine::ExecuteOperation()); //## @param point is the information of the seedpoint to add to the seedsimage //## @param last_point is the information of the point added before //## @param draw_state represents the seeds type e.g foreground or background seeds //## @param radius is the radius of seeds DrawOperation(OperationType operationType, Point3D point, Point3D last_point, int draw_state, int radius); virtual ~DrawOperation(); Point3D GetPoint(); Point3D GetLastPoint(); int GetDrawState(); int GetRadius(); SeedsImage::Pointer GetSeedsImage(); SeedsImage::Pointer GetLastSeedsImage(); private: Point3D m_Point; Point3D m_LastPoint; int m_DrawState; int m_Radius; SeedsImage::Pointer m_SeedsImage; SeedsImage::Pointer m_LastSeedsImage; }; }//namespace mitk #endif /* MITKDRAWOPERATION_H*/ diff --git a/Modules/MitkExt/DataManagement/mitkEllipsoid.cpp b/Modules/MitkExt/DataManagement/mitkEllipsoid.cpp index 8405b2fd22..a1ee3b75c6 100644 --- a/Modules/MitkExt/DataManagement/mitkEllipsoid.cpp +++ b/Modules/MitkExt/DataManagement/mitkEllipsoid.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 "mitkEllipsoid.h" #include "vtkLinearTransform.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "vtkSphereSource.h" mitk::Ellipsoid::Ellipsoid() : BoundingObject() { vtkSphereSource* sphere = vtkSphereSource::New(); sphere->SetRadius(1.0); sphere->SetThetaResolution(20); sphere->SetPhiResolution(20); sphere->Update(); SetVtkPolyData(sphere->GetOutput()); sphere->Delete(); } mitk::Ellipsoid::~Ellipsoid() { } bool mitk::Ellipsoid::IsInside(const Point3D& worldPoint) const { // transform point from world to object coordinates ScalarType p[4]; p[0] = worldPoint[0]; p[1] = worldPoint[1]; p[2] = worldPoint[2]; p[3] = 1; GetGeometry()->GetVtkTransform()->GetInverse()->TransformPoint(p, p); return (pow(p[0], 2) + pow(p[1], 2) + pow(p[2], 2) <= 1); } mitk::ScalarType mitk::Ellipsoid::GetVolume() { return GetGeometry()->GetExtentInMM(0) * 0.5 * GetGeometry()->GetExtentInMM(1) * 0.5 * GetGeometry()->GetExtentInMM(2) * 0.5 * vnl_math::pi * 4.0/3.0; } diff --git a/Modules/MitkExt/DataManagement/mitkMesh.cpp b/Modules/MitkExt/DataManagement/mitkMesh.cpp index 55cc2efcb8..3f800e1d55 100644 --- a/Modules/MitkExt/DataManagement/mitkMesh.cpp +++ b/Modules/MitkExt/DataManagement/mitkMesh.cpp @@ -1,840 +1,840 @@ /*=================================================================== 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 "mitkMesh.h" #include "mitkOperation.h" #include "mitkOperationActor.h" #include "mitkLineOperation.h" #include "mitkLineOperation.h" #include "mitkPointOperation.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkStatusBar.h" #include "mitkInteractionConst.h" #include "mitkLine.h" #include "mitkRenderingManager.h" mitk::Mesh::Mesh() { } mitk::Mesh::~Mesh() { } const mitk::Mesh::DataType *mitk::Mesh::GetMesh( int t ) const { return m_PointSetSeries[t]; } mitk::Mesh::DataType* mitk::Mesh::GetMesh( int t ) { return m_PointSetSeries[t]; } void mitk::Mesh::SetMesh( DataType *mesh, int t ) { this->Expand( t+1 ); m_PointSetSeries[t] = mesh; } unsigned long mitk::Mesh::GetNumberOfCells( int t ) { return m_PointSetSeries[t]->GetNumberOfCells(); } //search a line that is close enough according to the given position bool mitk::Mesh::SearchLine( Point3D point, float distance, unsigned long &lineId, unsigned long &cellId, int t ) { //returns true if a line is found ScalarType bestDist = distance; //iterate through all cells. ConstCellIterator cellIt = m_PointSetSeries[t]->GetCells()->Begin(); ConstCellIterator cellEnd = m_PointSetSeries[t]->GetCells()->End(); while( cellIt != cellEnd) { if (cellIt.Value()->GetNumberOfPoints() >1) { //then iterate through all indexes of points in it->Value() PointIdIterator inAIt = cellIt.Value()->PointIdsBegin(); // first point PointIdIterator inBIt = cellIt.Value()->PointIdsBegin(); // second point PointIdIterator inEnd = cellIt.Value()->PointIdsEnd(); ++inAIt; //so it points to the point before inBIt int currentLineId = 0; while(inAIt != inEnd) { mitk::PointSet::PointType pointA, pointB; if ( m_PointSetSeries[t]->GetPoint((*inAIt), &pointA) && m_PointSetSeries[t]->GetPoint((*inBIt), &pointB)) { Line *line = new Line(); line->SetPoints(pointA, pointB); double thisDistance = line->Distance(point); if (thisDistance < bestDist) { cellId = cellIt->Index(); lineId = currentLineId; bestDist = thisDistance; } } ++inAIt; ++inBIt; ++currentLineId; } // If the cell is closed, then check the line from the last index to // the first index if inAIt points to inEnd, then inBIt points to the // last index. CellDataType cellData; bool dataOk = m_PointSetSeries[t]->GetCellData(cellIt->Index(), &cellData); if (dataOk) { if (cellData.closed) { // get the points PointIdIterator inAIt = cellIt.Value()->PointIdsBegin();//first point // inBIt points to last. mitk::PointSet::PointType pointA, pointB; if ( m_PointSetSeries[t]->GetPoint((*inAIt), &pointA) && m_PointSetSeries[t]->GetPoint((*inBIt), &pointB)) { Line *line = new Line(); line->SetPoints(pointA, pointB); double thisDistance = line->Distance(point); if (thisDistance < bestDist) { cellId = cellIt->Index(); lineId = currentLineId; bestDist = thisDistance; } } } } } ++cellIt; } return (bestDist < distance); } int mitk::Mesh::SearchFirstCell( unsigned long pointId, int t ) { //iterate through all cells and find the cell the given pointId is inside ConstCellIterator it = m_PointSetSeries[t]->GetCells()->Begin(); ConstCellIterator end = m_PointSetSeries[t]->GetCells()->End(); while( it != end) { PointIdIterator position = std::find(it->Value()->PointIdsBegin(), it->Value()->PointIdsEnd(), pointId); if ( position != it->Value()->PointIdsEnd()) { return it->Index(); } ++it; } return -1; } // Due to not implemented itk::CellInterface::EvaluatePosition and errors in // using vtkCell::EvaluatePosition (changing iterator!) we must implement // it in mitk::Mesh // make it easy and look for hit points and hit lines: needs to be done anyway! bool mitk::Mesh::EvaluatePosition( mitk::Point3D point, unsigned long &cellId, float precision, int t ) { int pointId = this->SearchPoint( point, precision, t ); if (pointId > -1) { //search the cell the point lies inside cellId = this->SearchFirstCell( pointId, t ); return true; } unsigned long lineId = 0; if ( this->SearchLine(point, precision, lineId, cellId, t) ) { return true; } return false; } unsigned long mitk::Mesh::GetNewCellId( int t ) { long nextCellId = -1; ConstCellIterator it = m_PointSetSeries[t]->GetCells()->Begin(); ConstCellIterator end = m_PointSetSeries[t]->GetCells()->End(); while (it!=end) { nextCellId = it.Index(); ++it; } ++nextCellId; return nextCellId; } int mitk::Mesh::SearchSelectedCell( int t ) { CellDataIterator cellDataIt, cellDataEnd; cellDataEnd = m_PointSetSeries[t]->GetCellData()->End(); for ( cellDataIt = m_PointSetSeries[t]->GetCellData()->Begin(); cellDataIt != cellDataEnd; cellDataIt++ ) { //then declare an operation which unselects this line; UndoOperation as well! if ( cellDataIt->Value().selected ) { return cellDataIt->Index(); } } return -1; } // get the cell; then iterate through the Ids times lineId. Then IdA ist the // one, IdB ist ne next.don't forget the last closing line if the cell is // closed bool mitk::Mesh::GetPointIds( unsigned long cellId, unsigned long lineId, int &idA, int &idB, int t ) { bool ok = false; bool found = false; CellAutoPointer cellAutoPointer; ok = m_PointSetSeries[t]->GetCell(cellId, cellAutoPointer); if (ok) { CellType * cell = cellAutoPointer.GetPointer(); //Get the cellData to also check the closing line CellDataType cellData; m_PointSetSeries[t]->GetCellData(cellId, &cellData); bool closed = cellData.closed; PointIdIterator pointIdIt = cell->PointIdsBegin(); PointIdIterator pointIdEnd = cell->PointIdsEnd(); unsigned int counter = 0; while (pointIdIt != pointIdEnd) { if(counter == lineId) { idA = (*pointIdIt); ++pointIdIt; found = true; break; } ++counter; ++pointIdIt; } if(found) { //if in the middle if (pointIdIt != pointIdEnd) { idB = (*pointIdIt); } // if found but on the end, then it is the closing connection, so the // last and the first point else if (closed) { pointIdIt = cell->PointIdsBegin(); idB = (*pointIdIt); } } else ok = false; } return ok; } void mitk::Mesh::ExecuteOperation(Operation* operation) { //adding only the operations, that aren't implemented by the pointset. switch (operation->GetOperationType()) { case OpNOTHING: break; case OpNEWCELL: { mitk::LineOperation *lineOp = dynamic_cast(operation); // if no lineoperation, then call superclass pointSet if (lineOp == NULL) { Superclass::ExecuteOperation(operation); } bool ok; int cellId = lineOp->GetCellId(); CellAutoPointer cellAutoPointer; ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); // if it doesn't already exist if (!ok) { cellAutoPointer.TakeOwnership( new PolygonType ); m_PointSetSeries[0]->SetCell(cellId, cellAutoPointer); CellDataType cellData; cellData.selected = true; cellData.selectedLines.clear(); cellData.closed = false; m_PointSetSeries[0]->SetCellData(cellId, cellData); } } break; case OpDELETECELL: { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL)//if no lineoperation, then call superclass pointSet { Superclass::ExecuteOperation(operation); } m_PointSetSeries[0]->GetCells()->DeleteIndex((unsigned)lineOp->GetCellId()); m_PointSetSeries[0]->GetCellData()->DeleteIndex((unsigned)lineOp->GetCellId()); } break; case OpCLOSECELL: //sets the bolean flag closed from a specified cell to true. { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL)//if no lineoperation, then call superclass pointSet { //then search the selected cell!//TODO Superclass::ExecuteOperation(operation); } bool ok; int cellId = lineOp->GetCellId(); if (cellId<0)//cellId isn't set { cellId = this->SearchSelectedCell( 0 ); if (cellId < 0 )//still not found return; } CellAutoPointer cellAutoPointer; //get directly the celldata!TODO ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (ok) { CellDataType cellData; m_PointSetSeries[0]->GetCellData(cellId, &cellData); cellData.closed = true; m_PointSetSeries[0]->SetCellData(cellId, cellData); } } break; case OpOPENCELL: { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL)//if no lineoperation, then call superclass pointSet { Superclass::ExecuteOperation(operation); } bool ok; int cellId = lineOp->GetCellId(); CellAutoPointer cellAutoPointer; ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (ok) { CellDataType cellData; m_PointSetSeries[0]->GetCellData(cellId, &cellData); cellData.closed = false;; m_PointSetSeries[0]->SetCellData(cellId, cellData); } } break; case OpADDLINE: // inserts the ID of the selected point into the indexes of lines in the // selected cell afterwars the added line is selected { mitk::LineOperation *lineOp = dynamic_cast(operation); int cellId = -1; int pId = -1; if (lineOp == NULL) { cellId = this->SearchSelectedCell( 0 ); if (cellId == -1) return; pId = this->SearchSelectedPoint( 0 ); if (pId == -1) return; } else { cellId = lineOp->GetCellId(); if (cellId == -1) return; pId = lineOp->GetPIdA(); if (pId == -1) return; } bool ok; CellAutoPointer cellAutoPointer; ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (ok) { CellType * cell = cellAutoPointer.GetPointer(); if( cell->GetType() == CellType::POLYGON_CELL ) { PolygonType * polygon = static_cast( cell ); // add the pointId to the Cell. filling the empty cell with // one id doesn't mean to add a line, it means, that the // initilal PointId is set. The next addition of a pointId adds // a line polygon->AddPointId(pId); // select the line, if we really added a line, so now have more than // 1 pointID in the cell CellDataType cellData; ok = m_PointSetSeries[0]->GetCellData(cellId, &cellData); if (ok) { // A line between point 0 and 1 has the Id 0. A line between // 1 and 2 has a Id = 1. So we add getnumberofpoints-2. if (polygon->GetNumberOfPoints()>1) cellData.selectedLines.push_back(polygon->GetNumberOfPoints()-2); } m_PointSetSeries[0]->SetCellData(cellId, cellData); m_PointSetSeries[0]->SetCell(cellId, cellAutoPointer); } } } break; case OpDELETELINE: { // deleted the last line through removing the index PIdA // (if set to -1, use the last point) in the given cellId mitk::LineOperation *lineOp = dynamic_cast(operation); int cellId = -1; int pId = -1; if (lineOp == NULL) { cellId = this->SearchSelectedCell( 0 ); if (cellId == -1) return; pId = this->SearchSelectedPoint( 0 ); } else { cellId = lineOp->GetCellId(); if (cellId == -1) return; pId = lineOp->GetPIdA(); } bool ok; CellAutoPointer cellAutoPointer; ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (ok) { CellType * cell = cellAutoPointer.GetPointer(); if( cell->GetType() == CellType::POLYGON_CELL ) { PolygonType * oldPolygon = static_cast( cell ); PolygonType * newPolygonCell = new PolygonType; CellAutoPointer newCell; newCell.TakeOwnership( newPolygonCell ); PointIdConstIterator it, oldend; oldend = oldPolygon->PointIdsEnd(); if(pId >= 0) { for(it = oldPolygon->PointIdsBegin(); it != oldend; ++it) { if((*it) != (MeshType::PointIdentifier)pId) { newPolygonCell->AddPointId(*it); } } } else { --oldend; for(it = oldPolygon->PointIdsBegin(); it != oldend; ++it) newPolygonCell->AddPointId(*it); } oldPolygon->SetPointIds(0, newPolygonCell->GetNumberOfPoints(), newPolygonCell->PointIdsBegin()); } } } break; case OpREMOVELINE: //Remove the given Index in the given cell through copying everything // into a new cell accept the one that has to be deleted. { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL)//if no lineoperation, then call superclass pointSet { Superclass::ExecuteOperation(operation); } bool ok; CellAutoPointer cellAutoPointer; int cellId = lineOp->GetCellId(); ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (!ok) return; CellType * cell = cellAutoPointer.GetPointer(); CellAutoPointer newCellAutoPointer; newCellAutoPointer.TakeOwnership( new PolygonType ); PolygonType * newPolygon = static_cast( cell ); PointIdIterator it = cell->PointIdsBegin(); PointIdIterator end = cell->PointIdsEnd(); int pointId = lineOp->GetPIdA(); if (pointId<0)//if not initialized!! return; while (it!=end) { if ((*it)==(unsigned int)pointId) { break; } else { newPolygon ->AddPointId(*it); } ++it; } while (it!=end) { newPolygon ->AddPointId(*it); it++; } m_PointSetSeries[0]->SetCell(cellId, newCellAutoPointer); } break; case OpINSERTLINE: // //insert line between two other points. ////before A--B after A--C--B // //the points A, B and C have to be in the pointset. // //needed: CellId, Id of C , Id A and Id B ////the cell has to exist! //{ //mitk::LineOperation *lineOp = dynamic_cast(operation); // if (lineOp == NULL)//if no lineoperation, then call superclass pointSet // { // Superclass::ExecuteOperation(operation); // } // int cellId = lineOp->GetCellId(); // int pIdC = lineOp->GetPIdC(); // int pIdA = lineOp->GetPIdA(); // int pIdB = lineOp->GetPIdB(); // //the points of the given PointIds have to exist in the PointSet // bool ok; // ok = m_PointSetSeries[0]->GetPoints()->IndexExists(pIdA); // if (!ok) // return; // ok = m_PointSetSeries[0]->GetPoints()->IndexExists(pIdB); // if (!ok) // return; // ok = m_PointSetSeries[0]->GetPoints()->IndexExists(pIdC); // if (!ok) // return; // // so the points do exist. So now check, if there is already a cell // // with the given Id // DataType::CellAutoPointer cell; // ok = m_PointSetSeries[0]->GetCell(cellId, cell); // if (!ok) // return; // //pIdA and pIdB should exist in the cell // // PointIdIterator pit = cell->PointIdsBegin(); // PointIdIterator end = cell->PointIdsEnd(); // // //now arrange the new Ids in the cell like desired; pIdC between // // pIdA and pIdB // unsigned int nuPoints = cell->GetNumberOfPoints(); // std::vector newPoints; // pit = cell->PointIdsBegin(); // end = cell->PointIdsEnd(); // int i = 0; // while( pit != end ) // { // if ((*pit) = pIdA) // { // //now we have found the place to add pIdC after // newPoints[i] = (*pit); // i++; // newPoints[i] = pIdC; // } // else // newPoints[i] = (*pit); // pit++; // } // //now we have the Ids, that existed before combined with the new ones // //so delete the old cell // //doesn't seem to be necessary! // //cell->ClearPoints(); // pit = cell->PointIdsBegin(); // cell->SetPointIds(pit); //} break; case OpMOVELINE://(moves two points) { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL) { mitk::StatusBar::GetInstance()->DisplayText( "Message from mitkMesh: Recieved wrong type of operation! See mitkMeshInteractor.cpp", 10000); return; } //create two operations out of the one operation and call superclass //through the transmitted pointIds get the koordinates of the points. //then add the transmitted vestor to them //create two operations and send them to superclass Point3D pointA, pointB; pointA.Fill(0.0); pointB.Fill(0.0); m_PointSetSeries[0]->GetPoint(lineOp->GetPIdA(), &pointA); m_PointSetSeries[0]->GetPoint(lineOp->GetPIdB(), &pointB); pointA[0] += lineOp->GetVector()[0]; pointA[1] += lineOp->GetVector()[1]; pointA[2] += lineOp->GetVector()[2]; pointB[0] += lineOp->GetVector()[0]; pointB[1] += lineOp->GetVector()[1]; pointB[2] += lineOp->GetVector()[2]; mitk::PointOperation* operationA = new mitk::PointOperation(OpMOVE, pointA, lineOp->GetPIdA()); mitk::PointOperation* operationB = new mitk::PointOperation(OpMOVE, pointB, lineOp->GetPIdB()); Superclass::ExecuteOperation(operationA); Superclass::ExecuteOperation(operationB); } break; case OpSELECTLINE://(select the given line) { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL)//if no lineoperation, then call superclass pointSet { Superclass::ExecuteOperation(operation); } int cellId = lineOp->GetCellId(); CellAutoPointer cellAutoPointer; bool ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (ok) { CellDataType cellData; m_PointSetSeries[0]->GetCellData(cellId, &cellData); SelectedLinesType *selectedLines = &(cellData.selectedLines); SelectedLinesIter position = std::find(selectedLines->begin(), selectedLines->end(), (unsigned int) lineOp->GetId()); if (position == selectedLines->end())//if not alsready selected { cellData.selectedLines.push_back(lineOp->GetId()); } m_PointSetSeries[0]->SetCellData(lineOp->GetCellId(), cellData); } } break; case OpDESELECTLINE://(deselect the given line) { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL) { Superclass::ExecuteOperation(operation); } int cellId = lineOp->GetCellId(); CellAutoPointer cellAutoPointer; bool ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (ok) { CellDataType cellData; m_PointSetSeries[0]->GetCellData(cellId, &cellData); SelectedLinesType *selectedLines = &(cellData.selectedLines); SelectedLinesIter position = std::find(selectedLines->begin(), selectedLines->end(), (unsigned int) lineOp->GetId()); if (position != selectedLines->end())//if found { selectedLines->erase(position); } m_PointSetSeries[0]->SetCellData(cellId, cellData); } } break; case OpSELECTCELL://(select the given cell) { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL)//if no lineoperation, then call superclass pointSet { Superclass::ExecuteOperation(operation); } int cellId = lineOp->GetCellId(); CellAutoPointer cellAutoPointer; //directly get the data!//TODO bool ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (ok) { CellDataType cellData; m_PointSetSeries[0]->GetCellData(cellId, &cellData); cellData.selected = true; m_PointSetSeries[0]->SetCellData(cellId, cellData); } } break; case OpDESELECTCELL://(deselect the given cell) { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL)//if no lineoperation, then call superclass pointSet { Superclass::ExecuteOperation(operation); } int cellId = lineOp->GetCellId(); CellAutoPointer cellAutoPointer; bool ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (ok) { CellDataType cellData; m_PointSetSeries[0]->GetCellData(cellId, &cellData); cellData.selected = false; m_PointSetSeries[0]->SetCellData(cellId, cellData); } } break; case OpMOVECELL: //moves all Points of one cell according to the given vector { mitk::CellOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL)//if no celloperation, then call superclass pointSet { Superclass::ExecuteOperation(operation); } int cellId = lineOp->GetCellId(); Vector3D vector = lineOp->GetVector(); //get the cell CellAutoPointer cellAutoPointer; bool ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (!ok) return; CellDataType cellData; m_PointSetSeries[0]->GetCellData(cellId, &cellData); // iterate through the pointIds of the CellData and move those points in // the pointset PointIdIterator it = cellAutoPointer->PointIdsBegin(); PointIdIterator end = cellAutoPointer->PointIdsEnd(); while(it != end) { unsigned int position = (*it); PointType point; point.Fill(0); m_PointSetSeries[0]->GetPoint(position, &point); point = point + vector; m_PointSetSeries[0]->SetPoint(position, point); ++it; } } break; default: //if the operation couldn't be handled here, then send it to superclass Superclass::ExecuteOperation(operation); return; } //to tell the mappers, that the data is modifierd and has to be updated this->Modified(); mitk::OperationEndEvent endevent(operation); ((const itk::Object*)this)->InvokeEvent(endevent); // As discussed lately, don't mess with rendering from inside data structures //*todo has to be done here, cause of update-pipeline not working yet //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } mitk::Mesh::DataType::BoundingBoxPointer mitk::Mesh::GetBoundingBoxFromCell( unsigned long cellId, int t ) { // itk::CellInterface has also a GetBoundingBox, but it // returns CoordRepType [PointDimension *2] DataType::BoundingBoxPointer bBoxPointer = NULL; CellAutoPointer cellAutoPointer; if ( m_PointSetSeries[t]->GetCell(cellId, cellAutoPointer)) { DataType::PointsContainerPointer pointsContainer = DataType::PointsContainer::New(); PointIdIterator bbIt = cellAutoPointer.GetPointer()->PointIdsBegin(); PointIdIterator bbEnd = cellAutoPointer.GetPointer()->PointIdsEnd(); while(bbIt != bbEnd) { mitk::PointSet::PointType point; bool pointOk = m_PointSetSeries[t]->GetPoint((*bbIt), &point); if (pointOk) pointsContainer->SetElement((*bbIt), point); ++bbIt; } bBoxPointer = DataType::BoundingBoxType::New(); bBoxPointer->SetPoints(pointsContainer); bBoxPointer->ComputeBoundingBox(); } return bBoxPointer; } diff --git a/Modules/MitkExt/DataManagement/mitkNamedPoint.h b/Modules/MitkExt/DataManagement/mitkNamedPoint.h index 8aa471db49..4cb928f678 100644 --- a/Modules/MitkExt/DataManagement/mitkNamedPoint.h +++ b/Modules/MitkExt/DataManagement/mitkNamedPoint.h @@ -1,89 +1,89 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITK_NAMED_POINT_H #define MITK_NAMED_POINT_H -#include +#include #include namespace mitk { class NamedPoint{ std::string m_Name; mitk::Point3D m_Point; public: /** * */ NamedPoint() { }; /** * */ NamedPoint( const NamedPoint& namedPoint ) : m_Name( namedPoint.m_Name ), m_Point( namedPoint.m_Point ) { }; /** * */ NamedPoint( const std::string name, const Point3D& point ) : m_Name( name ), m_Point( point ) { }; /** * */ const std::string& GetName() const { return m_Name; }; /** * */ void SetName( const std::string& name ) { m_Name = name; }; /** * */ const Point3D& GetPoint() const { return m_Point; }; /** * */ void SetPoint( const Point3D& point ) { m_Point = point; }; }; } // mitk #endif // MITK_NAMED_POINT_H diff --git a/Modules/MitkExt/DataManagement/mitkPlane.cpp b/Modules/MitkExt/DataManagement/mitkPlane.cpp index 9605bf45d5..b26be9232f 100644 --- a/Modules/MitkExt/DataManagement/mitkPlane.cpp +++ b/Modules/MitkExt/DataManagement/mitkPlane.cpp @@ -1,113 +1,113 @@ /*=================================================================== 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 "mitkPlane.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include #include #include #include namespace mitk { Plane::Plane() : BoundingObject() { // Set up Plane Surface. m_PlaneSource = vtkPlaneSource::New(); m_PlaneSource->SetOrigin( -32.0, -32.0, 0.0 ); m_PlaneSource->SetPoint1( 32.0, -32.0, 0.0 ); m_PlaneSource->SetPoint2( -32.0, 32.0, 0.0 ); m_PlaneSource->SetResolution( 128, 128 ); m_PlaneSource->Update(); m_PlaneNormal = vtkDoubleArray::New(); m_PlaneNormal->SetNumberOfComponents( 3 ); m_PlaneNormal->SetNumberOfTuples( m_PlaneSource->GetOutput()->GetNumberOfPoints() ); m_PlaneNormal->SetTuple3( 0, 0.0, 0.0, 1.0 ); m_PlaneNormal->SetName( "planeNormal" ); m_Plane = vtkPolyData::New(); m_Plane->DeepCopy( m_PlaneSource->GetOutput() ); m_Plane->GetPointData()->SetVectors( m_PlaneNormal ); this->SetVtkPolyData( m_Plane ); } Plane::~Plane() { m_PlaneSource->Delete(); m_Plane->Delete(); m_PlaneNormal->Delete(); } void Plane::SetExtent( const double x, const double y ) { m_PlaneSource->SetOrigin( -x / 2.0, -y / 2.0, 0.0 ); m_PlaneSource->SetPoint1( x / 2.0, -y / 2.0, 0.0 ); m_PlaneSource->SetPoint2( -x / 2.0, y / 2.0, 0.0 ); m_PlaneSource->Update(); m_Plane->DeepCopy( m_PlaneSource->GetOutput() ); m_Plane->GetPointData()->SetVectors( m_PlaneNormal ); this->Modified(); } void Plane::GetExtent( double &x, double &y ) const { x = m_PlaneSource->GetPoint1()[0] - m_PlaneSource->GetOrigin()[0]; y = m_PlaneSource->GetPoint2()[1] - m_PlaneSource->GetOrigin()[1]; } void Plane::SetResolution( const int xR, const int yR ) { m_PlaneSource->SetResolution( xR, yR ); m_PlaneSource->Update(); m_Plane->DeepCopy( m_PlaneSource->GetOutput() ); m_Plane->GetPointData()->SetVectors( m_PlaneNormal ); this->Modified(); } void Plane::GetResolution( int &xR, int &yR ) const { m_PlaneSource->GetResolution( xR, yR ); } bool Plane::IsInside( const Point3D &/*worldPoint*/ ) const { // Plane does not have a volume return false; } ScalarType Plane::GetVolume() { // Plane does not have a volume return 0.0; } } diff --git a/Modules/MitkExt/DataManagement/mitkVecmathHelper.h b/Modules/MitkExt/DataManagement/mitkVecmathHelper.h index 9ba502e370..14abd35b0e 100644 --- a/Modules/MitkExt/DataManagement/mitkVecmathHelper.h +++ b/Modules/MitkExt/DataManagement/mitkVecmathHelper.h @@ -1,100 +1,100 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKVECHELPER_H_HEADER_INCLUDED_C1EBD0AD #define MITKVECHELPER_H_HEADER_INCLUDED_C1EBD0AD -#include "mitkVector.h" +#include "mitkTypes.h" #include "vecmath.h" namespace mitk { //itk vs. vecmath conversion template inline void vm2itk(const Point3& p, Point3D& a) { a[0]=p.x; a[1]=p.y; a[2]=p.z; } template inline void itk2vm(const Point3D& a, Point3 & p) { p.set(a[0], a[1], a[2]); } template inline void vm2itk(const Vector3& p, Vector3D& a) { a[0]=p.x; a[1]=p.y; a[2]=p.z; } template inline void itk2vm(const Vector3D& a, Vector3 & p) { p.set(a[0], a[1], a[2]); } template inline void vm2itk(const Vector3& p, VnlVector& a) { a[0]=p.x; a[1]=p.y; a[2]=p.z; } template inline void itk2vm(const VnlVector& a, Vector3 & p) { p.set(a[0], a[1], a[2]); } template inline void vtk2vm(const Tin a[3], Vector3 & p) { p.set(a[0], a[1], a[2]); } template inline void vm2vtk(const Vector3 & p, Tout a[3]) { a[0]=p.x; a[1]=p.y; a[2]=p.z; } template inline void vtk2vm(const Tin a[3], Point3 & p) { p.set(a[0], a[1], a[2]); } template inline void vm2vtk(const Point3 & p, Tout a[3]) { a[0]=p.x; a[1]=p.y; a[2]=p.z; } } // namespace mitk #endif /* MITKVECHELPER */ diff --git a/Modules/MitkExt/Interactions/mitkConnectPointsInteractor.h b/Modules/MitkExt/Interactions/mitkConnectPointsInteractor.h index dd97d0eac3..0e0112b9d7 100644 --- a/Modules/MitkExt/Interactions/mitkConnectPointsInteractor.h +++ b/Modules/MitkExt/Interactions/mitkConnectPointsInteractor.h @@ -1,97 +1,97 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKCONNECTPOINTSINTERACTOR_H_HEADER_INCLUDED_C11202FF #define MITKCONNECTPOINTSINTERACTOR_H_HEADER_INCLUDED_C11202FF #include "mitkCommon.h" #include "MitkExtExports.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include namespace mitk { class DataNode; //##Documentation //## @brief Interaction for mitk::Mesh: Connect existing points to lines //## @ingroup Interaction class MitkExt_EXPORT ConnectPointsInteractor : public Interactor { public: mitkClassMacro(ConnectPointsInteractor, Interactor); mitkNewMacro3Param(Self, const char*, DataNode*, int); mitkNewMacro2Param(Self, const char*, DataNode*); //##Documentation //## @brief Sets the amount of precision void SetPrecision( unsigned int precision ); //##Documentation //## @brief calculates how good the data, this statemachine handles, is hit by the event. //## //## overwritten, cause we don't look at the boundingbox, we look at each point virtual float CanHandleEvent(StateEvent const* stateEvent) const; protected: //##Documentation //##@brief Constructor with Param n for limited Set of Points //## //## if no n is set, then the number of points is unlimited* ConnectPointsInteractor(const char * type, DataNode* dataNode, int n = -1); virtual ~ConnectPointsInteractor(); virtual bool ExecuteAction( Action* action, mitk::StateEvent const* stateEvent ); //##Documentation //## @brief deselects the Points in the PointSet. //## supports Undo if enabled void UnselectAll(); //##Documentation //## @brief Selects the point. //## supports Undo if enabled. //## @param position is the index of the point that has to be selected void SelectPoint( int position ); private: //##Documentation //## @brief the number of possible points in this object //## //## if -1, then no limit set int m_N; //##Documentation //## @brief stores the current CellId this Statemachine works in unsigned int m_CurrentCellId; //##Documentation //## @brief to calculate a direction vector from last point and actual point Point3D m_LastPoint; //##Documentation //## @brief summ-vector for Movement Vector3D m_SumVec; //##Documentation //## @brief to store the value of precision to pick a point unsigned int m_Precision; }; } #endif /* MITKCONNECTPOINTSINTERACTOR_H_HEADER_INCLUDED_C11202FF */ diff --git a/Modules/MitkExt/Interactions/mitkDisplayPointSetInteractor.cpp b/Modules/MitkExt/Interactions/mitkDisplayPointSetInteractor.cpp index db8e95b7b8..24fcaccf5d 100644 --- a/Modules/MitkExt/Interactions/mitkDisplayPointSetInteractor.cpp +++ b/Modules/MitkExt/Interactions/mitkDisplayPointSetInteractor.cpp @@ -1,135 +1,135 @@ /*=================================================================== 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 "mitkDisplayPointSetInteractor.h" #include "mitkInteractionConst.h" #include "mitkStateEvent.h" #include "mitkBaseRenderer.h" -#include "mitkVector.h" +#include "mitkTypes.h" mitk::DisplayPointSetInteractor ::DisplayPointSetInteractor(const char * type, DataNode* dataNode, int n) :PointSetInteractor(type, dataNode, n) { } mitk::DisplayPointSetInteractor::~DisplayPointSetInteractor() { } bool mitk::DisplayPointSetInteractor ::ExecuteAction( Action* action, mitk::StateEvent const* stateEvent ) { bool ok = false;//for return type bool //get the timestep to also support 3D+T //const mitk::Event *theEvent = stateEvent->GetEvent(); /*Each case must watch the type of the event!*/ /*Each time a Point is added or removed or finished moved, the display-coordinates and the last renderer is stored.*/ switch (action->GetActionId()) { case AcADDPOINT: { mitk::DisplayPositionEvent const *posEvent = dynamic_cast < const mitk::DisplayPositionEvent * > (stateEvent->GetEvent()); if ( posEvent == NULL ) { return false; } m_LastDisplayCoordinates = posEvent->GetDisplayPosition(); m_LastRenderer = posEvent->GetSender(); ok = Superclass::ExecuteAction( action, stateEvent ); break; } case AcREMOVEPOINT://remove the given Point from the list { mitk::DisplayPositionEvent const *posEvent = dynamic_cast < const mitk::DisplayPositionEvent * > (stateEvent->GetEvent()); if ( posEvent == NULL ) { return false; } m_LastDisplayCoordinates = posEvent->GetDisplayPosition(); m_LastRenderer = posEvent->GetSender(); ok = Superclass::ExecuteAction( action, stateEvent ); break; } case AcREMOVEALL: { mitk::DisplayPositionEvent const *posEvent = dynamic_cast < const mitk::DisplayPositionEvent * > (stateEvent->GetEvent()); if ( posEvent == NULL ) { return false; } m_LastDisplayCoordinates = posEvent->GetDisplayPosition(); m_LastRenderer = posEvent->GetSender(); ok = Superclass::ExecuteAction( action, stateEvent ); break; } case AcFINISHMOVEMENT: { mitk::DisplayPositionEvent const *posEvent = dynamic_cast < const mitk::DisplayPositionEvent * > (stateEvent->GetEvent()); if ( posEvent == NULL ) { return false; } m_LastDisplayCoordinates = posEvent->GetDisplayPosition(); m_LastRenderer = posEvent->GetSender(); ok = Superclass::ExecuteAction( action, stateEvent ); break; } default: return Superclass::ExecuteAction( action, stateEvent ); } return ok; } mitk::Point2D mitk::DisplayPointSetInteractor::GetLastDisplayCoordinates() { return m_LastDisplayCoordinates; } mitk::BaseRenderer* mitk::DisplayPointSetInteractor::GetLastRenderer() { return m_LastRenderer; } diff --git a/Modules/MitkExt/Interactions/mitkDisplayPointSetInteractor.h b/Modules/MitkExt/Interactions/mitkDisplayPointSetInteractor.h index 2bbf70a7d3..e2cc423751 100644 --- a/Modules/MitkExt/Interactions/mitkDisplayPointSetInteractor.h +++ b/Modules/MitkExt/Interactions/mitkDisplayPointSetInteractor.h @@ -1,78 +1,78 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKDISPLAYPOINTSETINTERACTOR_H_HEADER_INCLUDED_C11202FF #define MITKDISPLAYPOINTSETINTERACTOR_H_HEADER_INCLUDED_C11202FF #include "mitkCommon.h" #include "MitkExtExports.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include #include "mitkPointSetInteractor.h" #include namespace mitk { class DataNode; /** * \brief Interaction with a set of points. * * Points can be added, removed and moved. * \ingroup Interaction */ class MitkExt_EXPORT DisplayPointSetInteractor : public PointSetInteractor { public: mitkClassMacro(DisplayPointSetInteractor, PointSetInteractor); mitkNewMacro3Param(Self, const char*, DataNode*, int); mitkNewMacro2Param(Self, const char*, DataNode*); Point2D GetLastDisplayCoordinates(); BaseRenderer* GetLastRenderer(); protected: /** * \brief Constructor with Param n for limited Set of Points * * if no n is set, then the number of points is unlimited* */ DisplayPointSetInteractor(const char * type, DataNode* dataNode, int n = -1); /** * \brief Default Destructor **/ virtual ~DisplayPointSetInteractor(); virtual bool ExecuteAction( Action* action, mitk::StateEvent const* stateEvent ); /** \brief last display-coordinates of the point * */ Point2D m_LastDisplayCoordinates; mitk::BaseRenderer* m_LastRenderer; }; } #endif /* MITKDisplayPointSetInteractor_H_HEADER_INCLUDED_C11202FF */ diff --git a/Modules/MitkExt/Interactions/mitkPointInteractor.h b/Modules/MitkExt/Interactions/mitkPointInteractor.h index b1cba5d710..b55c47e684 100644 --- a/Modules/MitkExt/Interactions/mitkPointInteractor.h +++ b/Modules/MitkExt/Interactions/mitkPointInteractor.h @@ -1,88 +1,88 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKPOINTINTERACTOR_H_HEADER_INCLUDED #define MITKPOINTINTERACTOR_H_HEADER_INCLUDED #include "mitkCommon.h" #include "MitkExtExports.h" #include -#include +#include namespace mitk { class DataNode; //##Documentation //## @brief Interaction with a point //## //## Interact with a point: set point, select point, move point and remove point //## All Set-operations are done through the method "ExecuteAction". //## the identificationnumber of this point is set by this points and evalued from an empty place in the DataStructure //## @ingroup Interaction class MitkExt_EXPORT PointInteractor : public Interactor { public: mitkClassMacro(PointInteractor, Interactor); mitkNewMacro2Param(Self, const char*, DataNode*); //##Documentation //## @brief Sets the amount of precision void SetPrecision(unsigned int precision); //##Documentation //## @brief derived from mitk::Interactor; calculates Jurisdiction according to points //## //## standard method can not be used, since it doesn't calculate in points, only in BoundingBox of Points virtual float CanHandleEvent(StateEvent const* stateEvent) const; protected: //##Documentation //##@brief Constructor PointInteractor(const char * type, DataNode* dataNode); //##Documentation //##@brief Destructor virtual ~PointInteractor(); //##Documentation //## @brief select the point on the given position virtual void SelectPoint(int position); //##Documentation //## @brief unselect all points that exist in mesh virtual void DeselectAllPoints(); //##Documentation //## @brief Executes Actions virtual bool ExecuteAction(Action* action, mitk::StateEvent const* stateEvent); private: //##Documentation //## @brief to calculate a direction vector from last point and actual point Point3D m_LastPoint; //##Documentation //## @brief to store a position unsigned int m_LastPosition; }; } #endif /* MITKPOINTINTERACTOR_H_HEADER_INCLUDED */ diff --git a/Modules/MitkExt/Interactions/mitkPointSelectorInteractor.h b/Modules/MitkExt/Interactions/mitkPointSelectorInteractor.h index 51c9a71e4f..d4c4c0a737 100644 --- a/Modules/MitkExt/Interactions/mitkPointSelectorInteractor.h +++ b/Modules/MitkExt/Interactions/mitkPointSelectorInteractor.h @@ -1,88 +1,88 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKPOINTSELECTORINTERACTOR_H_HEADER_INCLUDED #define MITKPOINTSELECTORINTERACTOR_H_HEADER_INCLUDED #include "mitkCommon.h" #include "MitkExtExports.h" #include -#include +#include namespace mitk { class DataNode; //##Documentation //## @brief Just select a point, that's the only way to interact with the point //## //## Interact with a point: Select the point without moving to get parameters that does not change //## All Set-operations would be done through the method "ExecuteAction", if there would be anyone. //## the identificationnumber of this point is set by this points and evalued from an empty place in the DataStructure //## @ingroup Interaction class MitkExt_EXPORT PointSelectorInteractor : public Interactor { public: mitkClassMacro(PointSelectorInteractor, Interactor); mitkNewMacro2Param(Self, const char*, DataNode*); //##Documentation //## @brief Sets the amount of precision void SetPrecision(unsigned int precision); //##Documentation //## @brief derived from mitk::Interactor; calculates Jurisdiction according to points //## //## standard method can not be used, since it doesn't calculate in points, only in BoundingBox of Points virtual float CanHandleEvent(StateEvent const* stateEvent) const; protected: //##Documentation //##@brief Constructor PointSelectorInteractor(const char * type, DataNode* dataNode); //##Documentation //##@brief Destructor virtual ~PointSelectorInteractor(); //##Documentation //## @brief select the point on the given position virtual void SelectPoint(int position); //##Documentation //## @brief unselect all points that exist in mesh virtual void DeselectAllPoints(); //##Documentation //## @brief Executes Actions virtual bool ExecuteAction(Action* action, mitk::StateEvent const* stateEvent); private: //##Documentation //## @brief to calculate a direction vector from last point and actual point Point3D m_LastPoint; //##Documentation //## @brief to store a position unsigned int m_LastPosition; }; } #endif /* MITKPointSelectorInteractor_H_HEADER_INCLUDED */ diff --git a/Modules/MitkExt/Interactions/mitkSeedsInteractor.h b/Modules/MitkExt/Interactions/mitkSeedsInteractor.h index dccec14cfe..21baf5732a 100644 --- a/Modules/MitkExt/Interactions/mitkSeedsInteractor.h +++ b/Modules/MitkExt/Interactions/mitkSeedsInteractor.h @@ -1,72 +1,72 @@ /*=================================================================== 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. ===================================================================*/ #ifndef __SeedsInteractor_H #define __SeedsInteractor_H #include #include "MitkExtExports.h" #include -#include +#include #include //needed by QmitkSimplexMeshes (SMDeformation.cpp and LungSegmentation.cpp) #include #include namespace mitk { //##Documentation //## @brief SeedsInteractor handles all actions on the seedsimage //## @ingroup Interaction class MitkExt_EXPORT SeedsInteractor : public Interactor { public: mitkClassMacro(SeedsInteractor, Interactor); mitkNewMacro2Param(Self, const char*, DataNode*); /// sets the radius of the seeds. void SetRadius(int val){m_Radius=val;}; void SetCurrentDrawState(int val){m_CurrentDrawState = val;}; itkSetMacro(Config, unsigned int); itkGetMacro(Config, unsigned int); protected: /** * @brief Default Constructor **/ SeedsInteractor(const char * type, DataNode* dataNode); /** * @brief Default Destructor **/ virtual ~SeedsInteractor(); virtual bool ExecuteAction(Action* action, StateEvent const* stateEvent); protected: SeedsImage::Pointer m_SeedsImage; SeedsImage::Pointer m_LastSeedsImage; Point3D event_point; Point3D last_point; int m_Radius; int m_DrawState; int m_CurrentDrawState; unsigned int m_Config; // determine whether 254,255 or smoothed float values are used. }; } #endif //__SeedsInteractor_H diff --git a/Modules/MitkExt/Interactions/mitkTDMouseEvent.cpp b/Modules/MitkExt/Interactions/mitkTDMouseEvent.cpp index d9baf59e39..a64b863683 100644 --- a/Modules/MitkExt/Interactions/mitkTDMouseEvent.cpp +++ b/Modules/MitkExt/Interactions/mitkTDMouseEvent.cpp @@ -1,25 +1,25 @@ /*=================================================================== 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 "mitkTDMouseEvent.h" #include "mitkInteractionConst.h" -#include "mitkVector.h" +#include "mitkTypes.h" mitk::TDMouseEvent::TDMouseEvent(int buttonState, const Vector3D& translation, const Vector3D& rotation, const ScalarType& angle) : Event(NULL, Type_TDMouseInput, BS_NoButton, buttonState, Key_none), m_Translation(translation), m_Rotation(rotation), m_Angle(angle) { } diff --git a/Modules/MitkExt/Interactions/mitkTDMouseEvent.h b/Modules/MitkExt/Interactions/mitkTDMouseEvent.h index 0df579907f..769b55a0e5 100644 --- a/Modules/MitkExt/Interactions/mitkTDMouseEvent.h +++ b/Modules/MitkExt/Interactions/mitkTDMouseEvent.h @@ -1,76 +1,76 @@ /*=================================================================== 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. ===================================================================*/ #ifndef TDMOUSEEVENT_H_HEADER_INCLUDED #define TDMOUSEEVENT_H_HEADER_INCLUDED #include "mitkCommon.h" #include "mitkEvent.h" -#include "mitkVector.h" +#include "mitkTypes.h" namespace mitk { //##Documentation //## @brief Event on 3D Mouse input //## //## Seven coordinates exposed by the 3D Mouse: //## 3-dimensional translation vector //## 3-dimensional rotation achsis (length allways 1.0) //## scalar rotation angle //## @ingroup Interaction class TDMouseEvent : public Event { public: //##Documentation //## @brief Constructor with all necessary arguments. //## //## buttonState: information from the Event TDMouseEvent(int buttonState, const Vector3D& translation, const Vector3D& rotation, const ScalarType& angle); const Vector3D& GetTranslation() const { return m_Translation; } void SetTranslation(const Vector3D& translation) { m_Translation = translation; } const Vector3D& GetRotation() const { return m_Rotation; } void SetRotation(const Vector3D& rotation) { m_Rotation = rotation; } const ScalarType& GetAngle() const { return m_Angle; } void SetAngle(const ScalarType& angle) { m_Angle = angle; } protected: Vector3D m_Translation; Vector3D m_Rotation; ScalarType m_Angle; }; } // namespace mitk #endif /* TDMOUSEEVENT_H_HEADER_INCLUDED */ diff --git a/Modules/MitkExt/Interactions/mitkTDMouseEventThrower.cpp b/Modules/MitkExt/Interactions/mitkTDMouseEventThrower.cpp index 3a01a2e2bc..504d2c1290 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 "mitkTypes.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 wird nicht initialisiert und kommt mit 0 zur�ck! 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/Modules/MitkExt/Interactions/mitkTDMouseEventThrower.h b/Modules/MitkExt/Interactions/mitkTDMouseEventThrower.h index 0189ed1594..6b916cbd31 100644 --- a/Modules/MitkExt/Interactions/mitkTDMouseEventThrower.h +++ b/Modules/MitkExt/Interactions/mitkTDMouseEventThrower.h @@ -1,44 +1,44 @@ /*=================================================================== 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. ===================================================================*/ #ifndef TDMouseEventThrower__h__ #define TDMouseEventThrower__h__ -#include +#include #include namespace mitk { class TDMouseEventThrower { public: static TDMouseEventThrower* GetInstance(); void DeviceChange (long device, long keys, long programmableKeys); void KeyDown (int keyCode); void KeyUp (int keyCode); void SensorInput( mitk::Vector3D translation, mitk::Vector3D rotation, mitk::ScalarType angle); protected: TDMouseEventThrower(); ~TDMouseEventThrower(); }; }//namespace #endif // TDMouseEventThrower__h__ diff --git a/Modules/MitkExt/Rendering/mitkEnhancedPointSetVtkMapper3D.h b/Modules/MitkExt/Rendering/mitkEnhancedPointSetVtkMapper3D.h index c72e8899e8..12e506c5c9 100644 --- a/Modules/MitkExt/Rendering/mitkEnhancedPointSetVtkMapper3D.h +++ b/Modules/MitkExt/Rendering/mitkEnhancedPointSetVtkMapper3D.h @@ -1,125 +1,125 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKEnhancedPointSetVtkMapper3D_H_HEADER_INCLUDED_C1907273 #define MITKEnhancedPointSetVtkMapper3D_H_HEADER_INCLUDED_C1907273 #include "mitkCommon.h" #include "MitkExtExports.h" #include "mitkVtkMapper.h" #include "mitkBaseRenderer.h" #include "mitkPointSet.h" -#include "mitkVector.h" +#include "mitkTypes.h" class vtkActor; class vtkAssembly; class vtkSphereSource; class vtkCubeSource; class vtkConeSource; class vtkCylinderSource; class vtkTubeFilter; class vtkProp; namespace mitk { /** * \brief Alternative Vtk-based 3D mapper for mitk::PointSet * * This class renders mitk::PointSet objects in 3D views. It resembles the * standard mitk::PointSetVtkMapper3D, but is designed to enable single * points to be rendered with individual appearances. * * Instead of assembling one vtkPolyData object containing all points, * a list of VTK source objects (spheres, cubes, cones, ...) is maintained. * Therefore, the application can change the appearance and/or type of a * specific point at runtime, without having to rebuild the * * You should use this class instead of the standard mapper if you * * - change the PointSet very often (by adding or removing points) * - need different representations for points (+++) * - want to change the point representation frequently (+++) * * Note: the class is still in experimental stage, and the points above * marked with (+++) are not yet working correctly. Also, drawing lines * between points (contour mode) is not yet supported. The class will be * extended so that point representations are stored in a lookup table, * which is indexed by point data from the rendered PointSet. * * \warn This mapper requires the PointData container to be the same size * as the point container. * * \sa PointSetVtkMapper3D */ class MitkExt_EXPORT EnhancedPointSetVtkMapper3D : public VtkMapper { public: mitkClassMacro(EnhancedPointSetVtkMapper3D, VtkMapper); itkNewMacro(Self); virtual const mitk::PointSet* GetInput(); virtual vtkProp* GetVtkProp(mitk::BaseRenderer* renderer); virtual void UpdateVtkTransform(mitk::BaseRenderer *renderer); static void SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer = NULL, bool overwrite = false); void ReleaseGraphicsResources(vtkWindow *renWin); LocalStorageHandler m_LSH; protected: EnhancedPointSetVtkMapper3D(); virtual ~EnhancedPointSetVtkMapper3D(); void RemoveEntryFromSourceMaps( mitk::PointSet::PointIdentifier pointID ); void DeleteVtkObject(vtkObject* o); // functor for stl_each in destructor // update all vtk sources, mappers, actors with current data and properties void UpdateVtkObjects(); virtual void GenerateDataForRenderer(mitk::BaseRenderer* renderer); virtual void ApplyProperties(mitk::BaseRenderer* renderer); typedef mitk::PointSet::PointIdentifier PointIdentifier; typedef std::map SphereSourceMap; typedef std::map CubeSourceMap; typedef std::map ConeSourceMap; typedef std::map CylinderSourceMap; typedef std::pair ActorAndPointType; typedef std::map ActorMap; SphereSourceMap m_SphereSources; // stores all sphere sources CubeSourceMap m_CubeSources; // stores all cube sources ConeSourceMap m_ConeSources; // stores all cone sources CylinderSourceMap m_CylinderSources; // stores all cylinder sources ActorMap m_PointActors; // stores an actor for each point(referenced by its ID) and the currently used pointspec = which source type is generating the polydata vtkActor* m_Contour; vtkTubeFilter* m_ContourSource; vtkAssembly* m_PropAssembly; // this contains everything, this will be returned by GetVtkProp() }; } // namespace mitk #endif /* MITKEnhancedPointSetVtkMapper3D_H_HEADER_INCLUDED_C1907273 */ diff --git a/Modules/MitkExt/Rendering/mitkSplineMapper2D.cpp b/Modules/MitkExt/Rendering/mitkSplineMapper2D.cpp index 18d1f35445..f9adb25921 100755 --- a/Modules/MitkExt/Rendering/mitkSplineMapper2D.cpp +++ b/Modules/MitkExt/Rendering/mitkSplineMapper2D.cpp @@ -1,193 +1,193 @@ /*=================================================================== 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 "mitkSplineMapper2D.h" #include "mitkSplineVtkMapper3D.h" #include -#include +#include #include #include #include #include #include #include void mitk::SplineMapper2D::Paint ( mitk::BaseRenderer * renderer ) { Superclass::Paint ( renderer ); bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if ( !visible ) return; // // get the poly data of the splines in 3D // mitk::SplineVtkMapper3D::Pointer mapper3D = dynamic_cast ( this->GetDataNode()->GetMapper ( 2 ) ); if ( mapper3D.IsNull() ) { itkWarningMacro ( "Mapper used for 3D mapping is not a mitk::SplineVtkMapper3D!" ); return; } // // update the 3D spline, if the accoring mapper has not been updated yet // //if ( mapper3D->GetLastUpdateTime() < GetDataNode()->GetData()->GetMTime() ) mapper3D->UpdateSpline(); vtkPolyData* spline3D = NULL; if ( mapper3D->SplinesAreAvailable() ) spline3D = mapper3D->GetSplinesPolyData(); else return; if ( spline3D == NULL ) { itkWarningMacro ( "3D spline is not available!" ); return; } // // get the transform associated with the data tree node // vtkLinearTransform* transform = this->GetDataNode()->GetVtkTransform(); if ( transform == NULL ) { itkWarningMacro("transfrom is NULL"); } // // get the plane geometry of the current renderer // mitk::Geometry2D::ConstPointer worldGeometry = renderer->GetCurrentWorldGeometry2D(); if ( worldGeometry.IsNull() ) { itkWarningMacro("worldGeometry is NULL!"); return; } PlaneGeometry::ConstPointer worldPlaneGeometry = dynamic_cast ( worldGeometry.GetPointer() ); if ( worldPlaneGeometry.IsNull() ) { itkWarningMacro("worldPlaneGeometry is NULL!"); return; } // // determine color of the spline // float color[3]; this->GetDataNode()->GetColor ( color, renderer ); // // iterate over the points // vtkPoints *vpoints = spline3D->GetPoints(); vtkCellArray *vlines = spline3D->GetLines(); if (vpoints == NULL) { itkWarningMacro("points are NULL!"); return; } if (vlines == NULL) { itkWarningMacro("lines are NULL!"); return; } mitk::Point3D currentPoint3D; mitk::Point2D currentPoint2D; vtkFloatingPointType currentPoint3DVtk[3]; vlines->InitTraversal(); int numberOfLines = vlines->GetNumberOfCells(); vtkFloatingPointType currentPointDistance; for ( int i = 0;i < numberOfLines; ++i ) { bool previousPointOnPlane = false; bool currentPointOnPlane = false; vtkIdType* cell ( NULL ); vtkIdType cellSize ( 0 ); vlines->GetNextCell ( cellSize, cell ); for ( int j = 0 ; j < cellSize; ++j ) { vpoints->GetPoint ( cell[j], currentPoint3DVtk ); // take transformation via vtktransform into account transform->TransformPoint ( currentPoint3DVtk, currentPoint3DVtk ); vtk2itk ( currentPoint3DVtk, currentPoint3D ); // check if the point has a distance to the plane // which is smaller than m_MaxProjectionDistance currentPointDistance = worldPlaneGeometry->DistanceFromPlane ( currentPoint3D ); if ( currentPointDistance < m_MaxProjectionDistance ) { currentPointOnPlane = true; //convert 3D point (in mm) to 2D point on slice (also in mm) worldGeometry->Map ( currentPoint3D, currentPoint2D ); //convert point (until now mm and in worldcoordinates) to display coordinates (units ) renderer->GetDisplayGeometry()->WorldToDisplay ( currentPoint2D, currentPoint2D ); } else currentPointOnPlane = false; // // check if we have to begin or end a GL_LINE // if ( ( previousPointOnPlane == false ) && ( currentPointOnPlane == true ) ) { glLineWidth ( m_LineWidth ); glColor3f ( color[0], color[1], color[2] ); glBegin ( GL_LINE_STRIP ); } else if ( ( previousPointOnPlane == true ) && ( currentPointOnPlane == false ) ) { glEnd (); glLineWidth ( 1.0 ); } // the current ponit is on the plane, add it as point to the // line segment if ( currentPointOnPlane == true ) { glVertex2f ( currentPoint2D[0], currentPoint2D[1] ); } previousPointOnPlane = currentPointOnPlane; } // the last point of the spline segment is on the plane, thus we have to // close the GL_LINE if ( previousPointOnPlane == true ) { glEnd (); glLineWidth ( 1.0 ); } previousPointOnPlane = false; } } void mitk::SplineMapper2D::ApplyProperties ( mitk::BaseRenderer* renderer ) { ApplyColorAndOpacityProperties ( renderer ); } mitk::SplineMapper2D::SplineMapper2D() { m_MaxProjectionDistance = 1; m_ShowDistantLines = false ; m_LineWidth = 1; } mitk::SplineMapper2D::~SplineMapper2D() {} diff --git a/Modules/MitkExt/Testing/mitkMeshTest.cpp b/Modules/MitkExt/Testing/mitkMeshTest.cpp index 4020866878..61b84cc49a 100644 --- a/Modules/MitkExt/Testing/mitkMeshTest.cpp +++ b/Modules/MitkExt/Testing/mitkMeshTest.cpp @@ -1,81 +1,81 @@ /*=================================================================== 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 -#include +#include #include #include #include int mitkMeshTest(int /*argc*/, char* /*argv*/[]) { //Create mesh mitk::Mesh::Pointer mesh; mesh = mitk::Mesh::New(); //try to get the itkmesh std::cout << "Create a mesh and try to get the itkMesh"; mitk::Mesh::DataType::Pointer itkdata = NULL; itkdata = mesh->GetMesh(); if (itkdata.IsNull()) { std::cout<<"[FAILED]"<GetSize() != 0) { std::cout<<"[FAILED]"<ExecuteOperation(doOp); //now check new condition! if ( (mesh->GetSize()!=1) || (!mesh->IndexExists(position))) { std::cout<<"[FAILED]"<GetPoint(position); if (tempPoint != point) { std::cout<<"[FAILED]"< #include #include -#include +#include #include #include int mitkPlaneFitTest(int, char*[] ) { //float bounds[]={0.0f,10.0f,0.0f,10.0f,0.0f,5.0f}; mitk::PlaneFit::Pointer PlaneFit = mitk::PlaneFit::New(); mitk::PointSet::Pointer PointSet = mitk::PointSet::New(); mitk::Geometry3D::Pointer Geometry3D = mitk::Geometry3D::New(); mitk::Point3D Point; //first without any point, then incrementally add points within thre points there will be a plane geometry std::cout <<"Start PlaneFitTest "<GetPointSet()->GetPoints()->InsertElement(position, Point); } //Set Input PlaneFit->SetInput(PointSet); const mitk::PointSet* testPointSet = PlaneFit->GetInput(); std::cout<<" Size test of Input Method: "; if( testPointSet->GetSize() == PointSet->GetSize() ) { std::cout<<"[PASSED]"<Update(); const mitk::Point3D ¢roid = PlaneFit->GetCentroid(); mitk::Point3D expectedCentroid; expectedCentroid[0]=2.5; expectedCentroid[1]=3.75; expectedCentroid[2]=2.5; if ( centroid == expectedCentroid ) { std::cout<<"[PASSED]"<( PlaneFit->GetOutput()->GetGeometry()); if( Geometry2D ) { std::cout<<"[PASSED]"< #include "itkObject.h" #include "itkObjectFactory.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "cv.h" /*! \brief UndistortCameraImage This class is used to undistort camera images. Before any undistortion the class has to be initialized using the functions: SetFocalLength(),SetPrinzipalPoint() and SetCameraDistortion(). After this you can either use UndistortPixel() to undistort a single pixel's coordinates or UndistortImage() to undistort an OpenCV image. A faster version of UndistortImage() is UndistortImageFast(), however, it has to be initialized once with SetUndistortImageFastInfo() instead of the Set... methods before use. \sa QmitkFunctionality \ingroup Functionalities */ namespace mitk { class MITK_OPENCVVIDEOSUPPORT_EXPORT UndistortCameraImage : public itk::Object { public: mitkClassMacro(UndistortCameraImage,itk::Object); itkNewMacro(Self); /// Initialization /// /* * Set the camera's intrinsic focal length */ void SetFocalLength(float fc_x, float fc_y) { m_fcX = fc_x; m_fcY = fc_y; } /* * Set the camera's intrinsic principal point */ void SetPrincipalPoint(float cc_x, float cc_y) { m_ccX = cc_x; m_ccY = cc_y; } /* * Set the camera's intrinsic distortion parameters */ void SetCameraDistortion(float kc1, float kc2, float kc3, float kc4) { m_distortionMatrixData[0] = kc1; m_distortionMatrixData[1] = kc2; m_distortionMatrixData[2] = kc3; m_distortionMatrixData[3] = kc4; } /* * Pre-Calculates matrices for the later use of UndistortImageFast() */ void InitRemapUndistortion(int sizeX, int sizeY); /// USAGE /// /* * Undistort a single pixel, returns undistorted pixel */ mitk::Point2D UndistortPixel(mitk::Point2D src); /* * Complete undistortion of an OpenCV image, including all calculations */ void UndistortImage(IplImage* src, IplImage* dst); /* * Complete undistortion of an OpenCV image, using pre-calculated matrices from SetUndistortImageFastInfo() * The use of only a source parameter will cause the source to be overwritten. * NOTE: Using the Fast undistortion methods does not require a initialization via the Set... methods. */ void UndistortImageFast( IplImage * src, IplImage* dst = NULL ); void SetUndistortImageFastInfo(float in_dF1, float in_dF2, float in_dPrincipalX, float in_dPrincipalY, float in_Dist[4], float ImageSizeX, float ImageSizeY); UndistortCameraImage(); virtual ~UndistortCameraImage(); protected: // principal point and focal length parameters float m_ccX, m_ccY, m_fcX, m_fcY; // undistortion parameters float m_distortionMatrixData[4]; // intrinsic camera parameters float m_intrinsicMatrixData[9]; // precalculated matrices for fast image undistortion with UndistortImageFast() CvMat * m_mapX, * m_mapY; // intrinsic and undistortion camera matrices CvMat m_intrinsicMatrix, m_distortionMatrix; // temp image IplImage * m_tempImage; CvMat *m_DistortionCoeffs; CvMat *m_CameraMatrix; }; } #endif diff --git a/Modules/PlanarFigure/Interactions/mitkPlanarFigureInteractor.h b/Modules/PlanarFigure/Interactions/mitkPlanarFigureInteractor.h index 01025ed2db..bfa96a78c1 100644 --- a/Modules/PlanarFigure/Interactions/mitkPlanarFigureInteractor.h +++ b/Modules/PlanarFigure/Interactions/mitkPlanarFigureInteractor.h @@ -1,202 +1,202 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKPLANARFIGUREINTERACTOR_H_HEADER_INCLUDED #define MITKPLANARFIGUREINTERACTOR_H_HEADER_INCLUDED #include "PlanarFigureExports.h" #include "mitkCommon.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkDataInteractor.h" #pragma GCC visibility push(default) #include #pragma GCC visibility pop namespace mitk { class DataNode; class Geometry2D; class DisplayGeometry; class PlanarFigure; class PositionEvent; class BaseRenderer; class InteractionPositionEvent; class StateMachineAction; #pragma GCC visibility push(default) // Define events for PlanarFigure interaction notifications itkEventMacro( PlanarFigureEvent, itk::AnyEvent ); itkEventMacro( StartPlacementPlanarFigureEvent, PlanarFigureEvent ); itkEventMacro( EndPlacementPlanarFigureEvent, PlanarFigureEvent ); itkEventMacro( SelectPlanarFigureEvent, PlanarFigureEvent ); itkEventMacro( StartInteractionPlanarFigureEvent, PlanarFigureEvent ); itkEventMacro( EndInteractionPlanarFigureEvent, PlanarFigureEvent ); itkEventMacro( StartHoverPlanarFigureEvent, PlanarFigureEvent ); itkEventMacro( EndHoverPlanarFigureEvent, PlanarFigureEvent ); itkEventMacro( ContextMenuPlanarFigureEvent, PlanarFigureEvent ); #pragma GCC visibility pop /** * \brief Interaction with mitk::PlanarFigure objects via control-points * * \ingroup Interaction */ class PlanarFigure_EXPORT PlanarFigureInteractor : public DataInteractor { public: mitkClassMacro(PlanarFigureInteractor, DataInteractor); itkNewMacro(Self); /** \brief Sets the amount of precision */ void SetPrecision( ScalarType precision ); /** \brief Sets the minimal distance between two control points. */ void SetMinimumPointDistance( ScalarType minimumDistance ); protected: PlanarFigureInteractor(); virtual ~PlanarFigureInteractor(); virtual void ConnectActionsAndFunctions(); //////// Conditions //////// bool CheckFigurePlaced( const InteractionEvent* interactionEvent ); bool CheckFigureHovering( const InteractionEvent* interactionEvent ); bool CheckControlPointHovering( const InteractionEvent* interactionEvent ); bool CheckSelection( const InteractionEvent* interactionEvent ); bool CheckPointValidity( const InteractionEvent* interactionEvent ); bool CheckFigureFinished( const InteractionEvent* interactionEvent ); bool CheckResetOnPointSelect( const InteractionEvent* interactionEvent ); bool CheckFigureOnRenderingGeometry( const InteractionEvent* interactionEvent ); bool CheckMinimalFigureFinished( const InteractionEvent* interactionEvent ); bool CheckFigureIsExtendable( const InteractionEvent* interactionEvent ); //////// Actions //////// bool FinalizeFigure( StateMachineAction*, InteractionEvent* interactionEvent ); bool MoveCurrentPoint(StateMachineAction*, InteractionEvent* interactionEvent); bool DeselectPoint(StateMachineAction*, InteractionEvent* interactionEvent); bool AddPoint(StateMachineAction*, InteractionEvent* interactionEvent); bool AddInitialPoint(StateMachineAction*, InteractionEvent* interactionEvent); bool SwitchToHovering( StateMachineAction*, InteractionEvent* interactionEvent ); bool SetPreviewPointPosition( StateMachineAction*, InteractionEvent* interactionEvent ); bool HidePreviewPoint( StateMachineAction*, InteractionEvent* interactionEvent ); bool HideControlPoints( StateMachineAction*, InteractionEvent* interactionEvent ); bool RemoveSelectedPoint(StateMachineAction*, InteractionEvent* interactionEvent); bool RequestContextMenu(StateMachineAction*, InteractionEvent* interactionEvent); bool SelectFigure( StateMachineAction*, InteractionEvent* interactionEvent ); bool SelectPoint( StateMachineAction*, InteractionEvent* interactionEvent ); bool EndInteraction( StateMachineAction*, InteractionEvent* interactionEvent ); /** \brief Used when clicking to determine if a point is too close to the previous point. */ bool IsMousePositionAcceptableAsNewControlPoint( const mitk::InteractionPositionEvent* positionEvent, const PlanarFigure* ); bool TransformPositionEventToPoint2D( const InteractionPositionEvent* positionEvent, const Geometry2D *planarFigureGeometry, Point2D &point2D ); bool TransformObjectToDisplay( const mitk::Point2D &point2D, mitk::Point2D &displayPoint, const mitk::Geometry2D *objectGeometry, const mitk::Geometry2D *rendererGeometry, const mitk::DisplayGeometry *displayGeometry ) const; /** \brief Returns true if the first specified point is in proximity of the line defined * the other two point; false otherwise. * * Proximity is defined as the rectangle around the line with pre-defined distance * from the line. */ bool IsPointNearLine( const mitk::Point2D& point, const mitk::Point2D& startPoint, const mitk::Point2D& endPoint, mitk::Point2D& projectedPoint ) const; /** \brief Returns true if the point contained in the passed event (in display coordinates) * is over the planar figure (with a pre-defined tolerance range); false otherwise. */ int IsPositionOverFigure( const InteractionPositionEvent* positionEvent, PlanarFigure *planarFigure, const Geometry2D *planarFigureGeometry, const Geometry2D *rendererGeometry, const DisplayGeometry *displayGeometry, Point2D& pointProjectedOntoLine) const; /** \brief Returns the index of the marker (control point) over which the point contained * in the passed event (in display coordinates) currently is; -1 if the point is not over * a marker. */ int IsPositionInsideMarker( const InteractionPositionEvent* positionEvent, const PlanarFigure *planarFigure, const Geometry2D *planarFigureGeometry, const Geometry2D *rendererGeometry, const DisplayGeometry *displayGeometry ) const; void LogPrintPlanarFigureQuantities( const PlanarFigure *planarFigure ); virtual void ConfigurationChanged(); private: /** \brief to store the value of precision to pick a point */ ScalarType m_Precision; /** \brief Store the minimal distance between two control points. */ ScalarType m_MinimumPointDistance; /** \brief True if the mouse is currently hovering over the image. */ bool m_IsHovering; bool m_LastPointWasValid; //mitk::PlanarFigure::Pointer m_PlanarFigure; }; } #endif // MITKPLANARFIGUREINTERACTOR_H_HEADER_INCLUDED diff --git a/Modules/SceneSerializationBase/BasePropertySerializer/mitkClippingPropertySerializer.cpp b/Modules/SceneSerializationBase/BasePropertySerializer/mitkClippingPropertySerializer.cpp index 17a49e17e4..aa86f7f86d 100644 --- a/Modules/SceneSerializationBase/BasePropertySerializer/mitkClippingPropertySerializer.cpp +++ b/Modules/SceneSerializationBase/BasePropertySerializer/mitkClippingPropertySerializer.cpp @@ -1,99 +1,99 @@ /*=================================================================== 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. ===================================================================*/ #ifndef mitkClippingPropertySerializer_h_included #define mitkClippingPropertySerializer_h_included #include "mitkBasePropertySerializer.h" #include "mitkClippingProperty.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "SceneSerializationBaseExports.h" namespace mitk { class SceneSerializationBase_EXPORT ClippingPropertySerializer : public BasePropertySerializer { public: mitkClassMacro( ClippingPropertySerializer, BasePropertySerializer ); itkNewMacro(Self); virtual TiXmlElement* Serialize() { if (const ClippingProperty* prop = dynamic_cast(m_Property.GetPointer())) { TiXmlElement* element = new TiXmlElement("clipping"); if (prop->GetClippingEnabled()) element->SetAttribute("enabled", "true"); else element->SetAttribute("enabled", "false"); TiXmlElement* originElement = new TiXmlElement("origin"); const Point3D origin = prop->GetOrigin(); originElement->SetDoubleAttribute("x", origin[0]); originElement->SetDoubleAttribute("y", origin[1]); originElement->SetDoubleAttribute("z", origin[2]); element->LinkEndChild(originElement); TiXmlElement* normalElement = new TiXmlElement("normal"); const Vector3D normal = prop->GetNormal(); normalElement->SetDoubleAttribute("x", normal[0]); normalElement->SetDoubleAttribute("y", normal[1]); normalElement->SetDoubleAttribute("z", normal[2]); element->LinkEndChild(normalElement); return element; } else return NULL; } virtual BaseProperty::Pointer Deserialize(TiXmlElement* element) { if (!element) return NULL; bool enabled = std::string(element->Attribute("enabled")) == "true"; TiXmlElement* originElement = element->FirstChildElement("origin"); if (originElement == NULL) return NULL; Point3D origin; if ( originElement->QueryDoubleAttribute( "x", &origin[0] ) != TIXML_SUCCESS ) return NULL; if ( originElement->QueryDoubleAttribute( "y", &origin[1] ) != TIXML_SUCCESS ) return NULL; if ( originElement->QueryDoubleAttribute( "z", &origin[2] ) != TIXML_SUCCESS ) return NULL; TiXmlElement* normalElement = element->FirstChildElement("normal"); if (normalElement == NULL) return NULL; Vector3D normal; if ( normalElement->QueryDoubleAttribute( "x", &normal[0] ) != TIXML_SUCCESS ) return NULL; if ( normalElement->QueryDoubleAttribute( "y", &normal[1] ) != TIXML_SUCCESS ) return NULL; if ( normalElement->QueryDoubleAttribute( "z", &normal[2] ) != TIXML_SUCCESS ) return NULL; ClippingProperty::Pointer cp = ClippingProperty::New(origin, normal); cp->SetClippingEnabled(enabled); return cp.GetPointer(); } protected: ClippingPropertySerializer() {} virtual ~ClippingPropertySerializer() {} }; } // namespace // important to put this into the GLOBAL namespace (because it starts with 'namespace mitk') MITK_REGISTER_SERIALIZER(ClippingPropertySerializer); #endif diff --git a/Modules/Segmentation/DataManagement/mitkContourElement.h b/Modules/Segmentation/DataManagement/mitkContourElement.h index 405ab4649a..8b887e1c8c 100644 --- a/Modules/Segmentation/DataManagement/mitkContourElement.h +++ b/Modules/Segmentation/DataManagement/mitkContourElement.h @@ -1,247 +1,247 @@ /*=================================================================== 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. ===================================================================*/ #ifndef _mitkContourElement_H_ #define _mitkContourElement_H_ #include "mitkCommon.h" #include "SegmentationExports.h" -#include +#include #include #include namespace mitk { /** \brief Represents a contour in 3D space. A ContourElement is consisting of linked vertices implicitely defining the contour. They are stored in a double ended queue making it possible to add vertices at front and end of the contour and to iterate in both directions. To mark a vertex as a special one it can be set as a control point. \Note It is highly not recommend to use this class directly as no secure mechanism is used here. Use mitk::ContourModel instead providing some additional features. */ class Segmentation_EXPORT ContourElement : public itk::LightObject { public: mitkClassMacro(ContourElement, itk::LightObject); itkNewMacro(Self); mitkCloneMacro(Self); // Data container representing vertices /** \brief Represents a single vertex of contour. */ struct ContourModelVertex { ContourModelVertex(mitk::Point3D &point, bool active=false) : Coordinates(point), IsControlPoint(active) { }; /** \brief Treat point special. */ bool IsControlPoint; /** \brief Coordinates in 3D space. */ mitk::Point3D Coordinates; }; // END Data container representing vertices typedef ContourModelVertex VertexType; typedef std::deque VertexListType; typedef VertexListType::iterator VertexIterator; typedef VertexListType::const_iterator ConstVertexIterator; // start of inline methods /** \brief Return a const iterator a the front. */ virtual ConstVertexIterator ConstIteratorBegin() { return this->m_Vertices->begin(); } /** \brief Return a const iterator a the end. */ virtual ConstVertexIterator ConstIteratorEnd() { return this->m_Vertices->end(); } /** \brief Return an iterator a the front. */ virtual VertexIterator IteratorBegin() { return this->m_Vertices->begin(); } /** \brief Return an iterator a the end. */ virtual VertexIterator IteratorEnd() { return this->m_Vertices->end(); } /** \brief Returns the number of contained vertices. */ virtual int GetSize() { return this->m_Vertices->size(); } // end of inline methods /** \brief Add a vertex at the end of the contour \param point - coordinates in 3D space. \param isControlPoint - is the vertex a special control point. */ virtual void AddVertex(mitk::Point3D &point, bool isControlPoint); /** \brief Add a vertex at the end of the contour \param vertex - a contour element vertex. */ virtual void AddVertex(VertexType &vertex); /** \brief Add a vertex at the front of the contour \param point - coordinates in 3D space. \param isControlPoint - is the vertex a control point. */ virtual void AddVertexAtFront(mitk::Point3D &point, bool isControlPoint); /** \brief Add a vertex at the front of the contour \param vertex - a contour element vertex. */ virtual void AddVertexAtFront(VertexType &vertex); /** \brief Add a vertex at a given index of the contour \param point - coordinates in 3D space. \param isControlPoint - is the vertex a special control point. \param index - the index to be inserted at. */ virtual void InsertVertexAtIndex(mitk::Point3D &point, bool isControlPoint, int index); /** \brief Returns the vertex a given index \param index */ virtual VertexType* GetVertexAt(int index); /** \brief Returns the approximate nearest vertex a given posoition in 3D space \param point - query position in 3D space. \param eps - the error bound for search algorithm. */ virtual VertexType* GetVertexAt(const mitk::Point3D &point, float eps); /** \brief Returns the container of the vertices. */ VertexListType* GetVertexList(); /** \brief Returns whether the contour element is empty. */ bool IsEmpty(); /** \brief Returns if the conour is closed or not. */ virtual bool IsClosed(); /** \brief Returns whether a given point is near a contour, according to eps. \param point - query position in 3D space. \param eps - the error bound for search algorithm. */ virtual bool IsNearContour(const mitk::Point3D &point, float eps); /** \brief Close the contour. Connect first with last element. */ virtual void Close(); /** \brief Open the contour. Disconnect first and last element. */ virtual void Open(); /** \brief Set the contours IsClosed property. \param isClosed - true = closed; false = open; */ virtual void SetIsClosed(bool isClosed); /** \brief Concatenate the contuor with a another contour. All vertices of the other contour will be added after last vertex. \param other - the other contour \param check - set it true to avoid intersections */ void Concatenate(mitk::ContourElement* other, bool check); /** \brief Remove the given vertex from the container if exists. \param vertex - the vertex to be removed. */ virtual bool RemoveVertex(VertexType* vertex); /** \brief Remove a vertex at given index within the container if exists. \param index - the index where the vertex should be removed. */ virtual bool RemoveVertexAt(int index); /** \brief Remove the approximate nearest vertex at given position in 3D space if one exists. \param point - query point in 3D space. \param eps - error bound for search algorithm. */ virtual bool RemoveVertexAt(mitk::Point3D &point, float eps); /** \brief Clear the storage container. */ virtual void Clear(); /** \brief Returns the approximate nearest vertex a given posoition in 3D space \param point - query position in 3D space. \param eps - the error bound for search algorithm. */ VertexType* BruteForceGetVertexAt(const mitk::Point3D &point, float eps); /** \brief Returns the approximate nearest vertex a given posoition in 3D space \param point - query position in 3D space. \param eps - the error bound for search algorithm. */ VertexType* OptimizedGetVertexAt(const mitk::Point3D &point, float eps); VertexListType* GetControlVertices(); /** \brief Uniformly redistribute control points with a given period (in number of vertices) \param vertex - the vertex around which the redistribution is done. \param period - number of vertices between control points. */ void RedistributeControlVertices(const VertexType* vertex, int period); protected: ContourElement(); ContourElement(const mitk::ContourElement &other); virtual ~ContourElement(); VertexListType* m_Vertices; //double ended queue with vertices bool m_IsClosed; }; } // namespace mitk #endif // _mitkContourElement_H_ diff --git a/Modules/Segmentation/DataManagement/mitkExtrudedContour.cpp b/Modules/Segmentation/DataManagement/mitkExtrudedContour.cpp index 700ac11a19..27d2251eea 100644 --- a/Modules/Segmentation/DataManagement/mitkExtrudedContour.cpp +++ b/Modules/Segmentation/DataManagement/mitkExtrudedContour.cpp @@ -1,368 +1,368 @@ /*=================================================================== 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 "mitkExtrudedContour.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include "mitkBaseProcess.h" #include #include #include #include #include #include #include #include #include #include //vtkButterflySubdivisionFilter * subdivs; #include #include #include #include #include mitk::ExtrudedContour::ExtrudedContour() : m_Contour(NULL), m_ClippingGeometry(NULL), m_AutomaticVectorGeneration(false) { GetTimeSlicedGeometry()->InitializeEvenlyTimed(1); FillVector3D(m_Vector, 0.0, 0.0, 1.0); m_RightVector.Fill(0.0); m_ExtrusionFilter = vtkLinearExtrusionFilter::New(); m_ExtrusionFilter->CappingOff(); m_ExtrusionFilter->SetExtrusionTypeToVectorExtrusion(); double vtkvector[3]={0,0,1}; // set extrusion vector m_ExtrusionFilter->SetVector(vtkvector); m_TriangleFilter = vtkTriangleFilter::New(); m_TriangleFilter->SetInput(m_ExtrusionFilter->GetOutput()); m_SubdivisionFilter = vtkLinearSubdivisionFilter::New(); m_SubdivisionFilter->SetInput(m_TriangleFilter->GetOutput()); m_SubdivisionFilter->SetNumberOfSubdivisions(4); m_ClippingBox = vtkPlanes::New(); m_ClipPolyDataFilter = vtkClipPolyData::New(); m_ClipPolyDataFilter->SetInput(m_SubdivisionFilter->GetOutput()); m_ClipPolyDataFilter->SetClipFunction(m_ClippingBox); m_ClipPolyDataFilter->InsideOutOn(); m_Polygon = vtkPolygon::New(); m_ProjectionPlane = mitk::PlaneGeometry::New(); } mitk::ExtrudedContour::~ExtrudedContour() { m_ClipPolyDataFilter->Delete(); m_ClippingBox->Delete(); m_SubdivisionFilter->Delete(); m_TriangleFilter->Delete(); m_ExtrusionFilter->Delete(); m_Polygon->Delete(); } bool mitk::ExtrudedContour::IsInside(const Point3D& worldPoint) const { static double polygonNormal[3]={0.0,0.0,1.0}; // project point onto plane float xt[3]; itk2vtk(worldPoint, xt); xt[0] = worldPoint[0]-m_Origin[0]; xt[1] = worldPoint[1]-m_Origin[1]; xt[2] = worldPoint[2]-m_Origin[2]; float dist=xt[0]*m_Normal[0]+xt[1]*m_Normal[1]+xt[2]*m_Normal[2]; xt[0] -= dist*m_Normal[0]; xt[1] -= dist*m_Normal[1]; xt[2] -= dist*m_Normal[2]; double x[3]; x[0] = xt[0]*m_Right[0]+xt[1]*m_Right[1]+xt[2]*m_Right[2]; x[1] = xt[0]*m_Down[0] +xt[1]*m_Down[1] +xt[2]*m_Down[2]; x[2] = 0; // determine whether it's in the selection loop and then evaluate point // in polygon only if absolutely necessary. if ( x[0] >= this->m_ProjectedContourBounds[0] && x[0] <= this->m_ProjectedContourBounds[1] && x[1] >= this->m_ProjectedContourBounds[2] && x[1] <= this->m_ProjectedContourBounds[3] && this->m_Polygon->PointInPolygon(x, m_Polygon->Points->GetNumberOfPoints(), ((vtkDoubleArray *)this->m_Polygon->Points->GetData())->GetPointer(0), (double*)const_cast(this)->m_ProjectedContourBounds, polygonNormal) == 1 ) return true; else return false; } mitk::ScalarType mitk::ExtrudedContour::GetVolume() { return -1.0; } void mitk::ExtrudedContour::UpdateOutputInformation() { if ( this->GetSource() ) { this->GetSource()->UpdateOutputInformation(); } if(GetMTime() > m_LastCalculateExtrusionTime) { BuildGeometry(); BuildSurface(); } //if ( ( m_CalculateBoundingBox ) && ( m_PolyDataSeries.size() > 0 ) ) // CalculateBoundingBox(); } void mitk::ExtrudedContour::BuildSurface() { if(m_Contour.IsNull()) { SetVtkPolyData(NULL); return; } // set extrusion contour vtkPolyData *polyData = vtkPolyData::New(); vtkCellArray *polys = vtkCellArray::New(); polys->InsertNextCell(m_Polygon->GetPointIds()); polyData->SetPoints(m_Polygon->GetPoints()); //float vtkpoint[3]; //unsigned int i, numPts = m_Polygon->GetNumberOfPoints(); //for(i=0; im_Polygon->Points->GetPoint(i); // pointids[i]=loopPoints->InsertNextPoint(vtkpoint); //} //polys->InsertNextCell( i, pointids ); //delete [] pointids; //polyData->SetPoints( loopPoints ); polyData->SetPolys( polys ); polys->Delete(); m_ExtrusionFilter->SetInput(polyData); polyData->Delete(); // set extrusion scale factor m_ExtrusionFilter->SetScaleFactor(GetGeometry()->GetExtentInMM(2)); SetVtkPolyData(m_SubdivisionFilter->GetOutput()); //if(m_ClippingGeometry.IsNull()) //{ // SetVtkPolyData(m_SubdivisionFilter->GetOutput()); //} //else //{ // m_ClipPolyDataFilter->SetInput(m_SubdivisionFilter->GetOutput()); // mitk::BoundingBox::BoundsArrayType bounds=m_ClippingGeometry->GetBounds(); // m_ClippingBox->SetBounds(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]); // m_ClippingBox->SetTransform(GetGeometry()->GetVtkTransform()); // m_ClipPolyDataFilter->SetClipFunction(m_ClippingBox); // m_ClipPolyDataFilter->SetValue(0); // SetVtkPolyData(m_ClipPolyDataFilter->GetOutput()); //} m_LastCalculateExtrusionTime.Modified(); } void mitk::ExtrudedContour::BuildGeometry() { if(m_Contour.IsNull()) return; // Initialize(1); Vector3D nullvector; nullvector.Fill(0.0); float xProj[3]; unsigned int i; unsigned int numPts = 20; //m_Contour->GetNumberOfPoints(); mitk::Contour::PathPointer path = m_Contour->GetContourPath(); mitk::Contour::PathType::InputType cstart = path->StartOfInput(); mitk::Contour::PathType::InputType cend = path->EndOfInput(); mitk::Contour::PathType::InputType cstep = (cend-cstart)/numPts; mitk::Contour::PathType::InputType ccur; // Part I: guarantee/calculate legal vectors m_Vector.Normalize(); itk2vtk(m_Vector, m_Normal); // check m_Vector if(mitk::Equal(m_Vector, nullvector) || m_AutomaticVectorGeneration) { if ( m_AutomaticVectorGeneration == false) itkWarningMacro("Extrusion vector is 0 ("<< m_Vector << "); trying to use normal of polygon"); vtkPoints *loopPoints = vtkPoints::New(); //mitk::Contour::PointsContainerIterator pointsIt = m_Contour->GetPoints()->Begin(); double vtkpoint[3]; unsigned int i=0; for(i=0, ccur=cstart; iEvaluate(ccur), vtkpoint); loopPoints->InsertNextPoint(vtkpoint); } // Make sure points define a loop with a m_Normal vtkPolygon::ComputeNormal(loopPoints, m_Normal); loopPoints->Delete(); vtk2itk(m_Normal, m_Vector); if(mitk::Equal(m_Vector, nullvector)) { itkExceptionMacro("Cannot calculate normal of polygon"); } } // check m_RightVector if((mitk::Equal(m_RightVector, nullvector)) || (mitk::Equal(m_RightVector*m_Vector, 0.0)==false)) { if(mitk::Equal(m_RightVector, nullvector)) { itkDebugMacro("Right vector is 0. Calculating."); } else { itkWarningMacro("Right vector ("<InitializeStandardPlane(rightDV, downDV); // create vtkPolygon from contour and simultaneously determine 2D bounds of // contour projected on m_ProjectionPlane //mitk::Contour::PointsContainerIterator pointsIt = m_Contour->GetPoints()->Begin(); m_Polygon->Points->Reset(); m_Polygon->Points->SetNumberOfPoints(numPts); m_Polygon->PointIds->Reset(); m_Polygon->PointIds->SetNumberOfIds(numPts); mitk::Point2D pt2d; mitk::Point3D pt3d; mitk::Point2D min, max; min.Fill(ScalarTypeNumericTraits::max()); max.Fill(ScalarTypeNumericTraits::min()); xProj[2]=0.0; for(i=0, ccur=cstart; iEvaluate(ccur)); m_ProjectionPlane->Map(pt3d, pt2d); xProj[0]=pt2d[0]; if(pt2d[0]max[0]) max[0]=pt2d[0]; xProj[1]=pt2d[1]; if(pt2d[1]max[1]) max[1]=pt2d[1]; m_Polygon->Points->SetPoint(i, xProj); m_Polygon->PointIds->SetId(i, i); } // shift parametric origin to (0,0) for(i=0; im_Polygon->Points->GetPoint(i); pt[0]-=min[0]; pt[1]-=min[1]; itkDebugMacro( << i << ": (" << pt[0] << "," << pt[1] << "," << pt[2] << ")" ); } this->m_Polygon->GetBounds(m_ProjectedContourBounds); //m_ProjectedContourBounds[4]=-1.0; m_ProjectedContourBounds[5]=1.0; // calculate origin (except translation along the normal) and bounds // of m_ProjectionPlane: // origin is composed of the minimum x-/y-coordinates of the polygon, // bounds from the extent of the polygon, both after projecting on the plane mitk::Point3D origin; m_ProjectionPlane->Map(min, origin); ScalarType bounds[6]={0, max[0]-min[0], 0, max[1]-min[1], 0, 1}; m_ProjectionPlane->SetBounds(bounds); m_ProjectionPlane->SetOrigin(origin); // Part III: initialize geometry if(m_ClippingGeometry.IsNotNull()) { ScalarType min_dist=ScalarTypeNumericTraits::max(), max_dist=ScalarTypeNumericTraits::min(), dist; unsigned char i; for(i=0; i<8; ++i) { dist = m_ProjectionPlane->SignedDistance( m_ClippingGeometry->GetCornerPoint(i) ); if(distmax_dist) max_dist=dist; } //incorporate translation along the normal into origin origin = origin+m_Vector*min_dist; m_ProjectionPlane->SetOrigin(origin); bounds[5]=max_dist-min_dist; } else bounds[5]=20; itk2vtk(origin, m_Origin); mitk::TimeSlicedGeometry::Pointer timeGeometry = this->GetTimeSlicedGeometry(); mitk::Geometry3D::Pointer g3d = timeGeometry->GetGeometry3D( 0 ); assert( g3d.IsNotNull() ); g3d->SetBounds(bounds); g3d->SetIndexToWorldTransform(m_ProjectionPlane->GetIndexToWorldTransform()); g3d->TransferItkToVtkTransform(); timeGeometry->InitializeEvenlyTimed(g3d, 1); } unsigned long mitk::ExtrudedContour::GetMTime() const { unsigned long latestTime = Superclass::GetMTime(); if(m_Contour.IsNotNull()) { unsigned long localTime; localTime = m_Contour->GetMTime(); if(localTime > latestTime) latestTime = localTime; } return latestTime; } diff --git a/Modules/Segmentation/Interactions/mitkContourInteractor.h b/Modules/Segmentation/Interactions/mitkContourInteractor.h index 1048c37a61..073acc481e 100644 --- a/Modules/Segmentation/Interactions/mitkContourInteractor.h +++ b/Modules/Segmentation/Interactions/mitkContourInteractor.h @@ -1,65 +1,65 @@ /*=================================================================== 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. ===================================================================*/ #ifndef __ContourInteractor_H #define __ContourInteractor_H #include "mitkCommon.h" #include "SegmentationExports.h" #include -#include +#include namespace mitk { //##Documentation //## @brief Interactor for the creation of an mitk::Contour //## @ingroup Interaction class Segmentation_EXPORT ContourInteractor : public mitk::Interactor { public: mitkClassMacro(ContourInteractor, Interactor); mitkNewMacro2Param(Self, const char*, DataNode*); protected: ContourInteractor(const char * type, DataNode* dataNode); virtual ~ContourInteractor(); virtual bool ExecuteAction(Action* action, mitk::StateEvent const* stateEvent); /** * entry method for any interaction. Method is called if user * presses the left mouse button down. */ virtual void Press (mitk::Point3D& op); /** * this method is finally called after user release the left mouse button */ virtual void Release (mitk::Point3D& op); /** * method is called when the user moves the mouse with left mouse button down */ virtual void Move (mitk::Point3D& op); protected: bool m_Positive; bool m_Started; }; } #endif //__ContourInteractor_H diff --git a/Modules/Segmentation/Interactions/mitkExtrudedContourInteractor.h b/Modules/Segmentation/Interactions/mitkExtrudedContourInteractor.h index 3996729cbf..b5990ec0c7 100644 --- a/Modules/Segmentation/Interactions/mitkExtrudedContourInteractor.h +++ b/Modules/Segmentation/Interactions/mitkExtrudedContourInteractor.h @@ -1,72 +1,72 @@ /*=================================================================== 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. ===================================================================*/ #ifndef __ExtrudedContourInteractor_H #define __ExtrudedContourInteractor_H #include "mitkCommon.h" #include "SegmentationExports.h" #include -#include +#include #include #include namespace mitk { //##Documentation //## @brief Interactor for the creation of an mitk::Contour //## @ingroup Interaction class Segmentation_EXPORT ExtrudedContourInteractor : public mitk::Interactor { public: mitkClassMacro(ExtrudedContourInteractor, Interactor); mitkNewMacro2Param(Self, const char*, DataNode*); itkGetObjectMacro(Contour, mitk::Contour); itkGetObjectMacro(ContourNode, mitk::DataNode); protected: ExtrudedContourInteractor(const char * type, DataNode* dataNode); virtual ~ExtrudedContourInteractor(); virtual bool ExecuteAction(Action* action, mitk::StateEvent const* stateEvent); /** * entry method for any interaction. Method is called if user * presses the left mouse button down. */ virtual void Press (mitk::Point3D& op); /** * this method is finally called after user release the left mouse button */ virtual void Release (mitk::Point3D& op); /** * method is called when the user moves the mouse with left mouse button down */ virtual void Move (mitk::Point3D& op); protected: bool m_Positive; bool m_Started; mitk::Contour::Pointer m_Contour; mitk::DataNode::Pointer m_ContourNode; }; } #endif //__ExtrudedContourInteractor_H diff --git a/Modules/ToFProcessing/Testing/mitkKinectReconstructionTest.cpp b/Modules/ToFProcessing/Testing/mitkKinectReconstructionTest.cpp index 1cdc7ba2a6..2c30032627 100644 --- a/Modules/ToFProcessing/Testing/mitkKinectReconstructionTest.cpp +++ b/Modules/ToFProcessing/Testing/mitkKinectReconstructionTest.cpp @@ -1,69 +1,69 @@ /*=================================================================== 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 #include #include #include #include -#include +#include #include #include #include #include #include /** * @brief mitkKinectReconstructionTest Testing method for the Kinect reconstruction mode. Specially meant for Kinect. * This tests loads a special data set from MITK-Data and compares it to a previously generated surface. * This test has no dependency to the mitkKinectModule, although it is thematically connected to it. */ int mitkKinectReconstructionTest(int argc , char* argv[]) { MITK_TEST_BEGIN("mitkKinectReconstructionTest"); MITK_TEST_CONDITION_REQUIRED(argc > 3, "Testing if enough arguments are set."); std::string calibrationFilePath(argv[1]); std::string kinectImagePath(argv[2]); std::string groundTruthSurfacePath(argv[3]); mitk::ToFDistanceImageToSurfaceFilter::Pointer distToSurf = mitk::ToFDistanceImageToSurfaceFilter::New(); mitk::CameraIntrinsics::Pointer intrinsics = mitk::CameraIntrinsics::New(); //load our personal kinect calibration intrinsics->FromXMLFile(calibrationFilePath); MITK_TEST_CONDITION_REQUIRED(intrinsics.IsNotNull(), "Testing if a calibration file could be loaded."); distToSurf->SetCameraIntrinsics(intrinsics); distToSurf->SetReconstructionMode(mitk::ToFDistanceImageToSurfaceFilter::Kinect); //load a data set mitk::Image::Pointer kinectImage = mitk::IOUtil::LoadImage(kinectImagePath); MITK_TEST_CONDITION_REQUIRED(kinectImage.IsNotNull(), "Testing if a kinect image could be loaded."); distToSurf->SetInput(kinectImage); distToSurf->Update(); //load ground truth data mitk::Surface::Pointer groundTruth = mitk::IOUtil::LoadSurface(groundTruthSurfacePath); MITK_TEST_CONDITION_REQUIRED(groundTruth.IsNotNull(), "Testing if ground truth could be loaded."); mitk::Surface::Pointer resultOfFilter = distToSurf->GetOutput(); MITK_TEST_CONDITION_REQUIRED(resultOfFilter.IsNotNull(), "Testing if any output was generated."); MITK_TEST_CONDITION_REQUIRED( mitk::ToFTestingCommon::VtkPolyDatasEqual(resultOfFilter->GetVtkPolyData(), groundTruth->GetVtkPolyData() ), "Testing if point sets are equal (with a small epsilon)."); MITK_TEST_END(); } diff --git a/Modules/ToFProcessing/Testing/mitkToFDistanceImageToPointSetFilterTest.cpp b/Modules/ToFProcessing/Testing/mitkToFDistanceImageToPointSetFilterTest.cpp index 7edac5e3b8..fe071a30fe 100644 --- a/Modules/ToFProcessing/Testing/mitkToFDistanceImageToPointSetFilterTest.cpp +++ b/Modules/ToFProcessing/Testing/mitkToFDistanceImageToPointSetFilterTest.cpp @@ -1,309 +1,309 @@ /*=================================================================== 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 #include #include #include #include #include #include #include -#include +#include #include #include #include #include /**Documentation * test for the class "ToFDistanceImageToPointSetFilter". */ mitk::PointSet::Pointer CreateTestPointSet() { mitk::PointSet::Pointer subSet = mitk::PointSet::New(); mitk::Point3D point; point[0] = 10; point[1] = 20; point[2] = 0; subSet->InsertPoint(0,point); point[0] = 100; point[1] = 150; point[2] = 0; subSet->InsertPoint(1,point); point[0] = 110; point[1] = 30; point[2] = 0; subSet->InsertPoint(2,point); point[0] = 40; point[1] = 200; point[2] = 0; subSet->InsertPoint(3,point); return subSet; } // Create image with pixelValue in every pixel except for the pixels in subSet, which get successively the values of distances inline static mitk::Image::Pointer CreateTestImageWithPointSet(mitk::ScalarType pixelValue, unsigned int dimX, unsigned int dimY, mitk::PointSet::Pointer subSet) { typedef itk::Image ItkImageType2D; typedef itk::ImageRegionIterator ItkImageRegionIteratorType2D; ItkImageType2D::Pointer image = ItkImageType2D::New(); ItkImageType2D::IndexType start; start[0] = 0; start[1] = 0; ItkImageType2D::SizeType size; size[0] = dimX; size[1] = dimY; ItkImageType2D::RegionType region; region.SetSize(size); region.SetIndex( start); ItkImageType2D::SpacingType spacing; spacing[0] = 1.0; spacing[1] = 1.0; image->SetRegions( region ); image->SetSpacing ( spacing ); image->Allocate(); //Obtaining image data from ToF camera// //Correlate inten values to PixelIndex// ItkImageRegionIteratorType2D imageIterator(image,image->GetLargestPossibleRegion()); imageIterator.GoToBegin(); while (!imageIterator.IsAtEnd()) { imageIterator.Set(pixelValue); ++imageIterator; } // distances varying from pixelValue std::vector distances; distances.push_back(50); distances.push_back(500); distances.push_back(2050); distances.push_back(300); // set the pixel values for the subset for(int i=0; iGetSize(); i++) { mitk::Point3D point = subSet->GetPoint(i); ItkImageType2D::IndexType index; index[0] = point[0]; index[1] = point[1]; mitk::ScalarType distance = distances.at(i); image->SetPixel(index,distance); } mitk::Image::Pointer mitkImage = mitk::Image::New(); mitk::CastToMitkImage(image,mitkImage); return mitkImage; } int mitkToFDistanceImageToPointSetFilterTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("ToFDistanceImageToPointSetFilter"); mitk::ToFDistanceImageToPointSetFilter::Pointer filter = mitk::ToFDistanceImageToPointSetFilter::New(); //create test sub set MITK_INFO<<"Create test pointset"; mitk::PointSet::Pointer subSet = CreateTestPointSet(); //create test image unsigned int dimX = 204; unsigned int dimY = 204; MITK_INFO<<"Create test image"; mitk::Image::Pointer image = CreateTestImageWithPointSet(1000.0f,dimX,dimY,subSet); //initialize intrinsic parameters //initialize intrinsic parameters with some arbitrary values mitk::ToFProcessingCommon::ToFPoint2D interPixelDistance; interPixelDistance[0] = 0.04564; interPixelDistance[1] = 0.0451564; mitk::ToFProcessingCommon::ToFScalarType focalLengthX = 295.78960; mitk::ToFProcessingCommon::ToFScalarType focalLengthY = 296.348535; mitk::ToFProcessingCommon::ToFScalarType focalLength = (focalLengthX*interPixelDistance[0]+focalLengthY*interPixelDistance[1])/2.0; mitk::ToFProcessingCommon::ToFScalarType k1=-0.36,k2=-0.14,p1=0.001,p2=-0.00; mitk::ToFProcessingCommon::ToFPoint2D principalPoint; principalPoint[0] = 103.576546; principalPoint[1] = 100.1532; mitk::CameraIntrinsics::Pointer cameraIntrinsics = mitk::CameraIntrinsics::New(); cameraIntrinsics->SetFocalLength(focalLengthX,focalLengthY); cameraIntrinsics->SetPrincipalPoint(principalPoint[0],principalPoint[1]); cameraIntrinsics->SetDistorsionCoeffs(k1,k2,p1,p2); // test SetCameraIntrinsics() filter->SetCameraIntrinsics(cameraIntrinsics); MITK_TEST_CONDITION_REQUIRED((focalLengthX==filter->GetCameraIntrinsics()->GetFocalLengthX()),"Testing SetCameraIntrinsics with focalLength"); mitk::ToFProcessingCommon::ToFPoint2D pp; pp[0] = filter->GetCameraIntrinsics()->GetPrincipalPointX(); pp[1] = filter->GetCameraIntrinsics()->GetPrincipalPointY(); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(principalPoint,pp),"Testing SetCameraIntrinsics with principalPoint()"); // test SetInterPixelDistance() filter->SetInterPixelDistance(interPixelDistance); mitk::ToFProcessingCommon::ToFPoint2D ipD = filter->GetInterPixelDistance(); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(ipD,interPixelDistance),"Testing Set/GetInterPixelDistance()"); // test SetReconstructionMode() filter->SetReconstructionMode(false); MITK_TEST_CONDITION_REQUIRED(filter->GetReconstructionMode() == false,"Testing Set/GetReconstructionMode()"); // test Set/GetInput() filter->SetInput(image); MITK_TEST_CONDITION_REQUIRED((image==filter->GetInput()),"Testing Set/GetInput()"); // test filter without subset (without using the interpixeldistance) MITK_INFO<<"Test filter without subset without using the interpixeldistance"; filter->SetReconstructionMode(true); mitk::PointSet::Pointer expectedResult = mitk::PointSet::New(); unsigned int counter = 0; mitk::ImagePixelReadAccessor imageAcces(image, image->GetSliceData(0)); for (unsigned int j=0; j index; index[0] = i; index[1] = j; mitk::ScalarType distance = imageAcces.GetPixelByIndex(index); mitk::Point3D coordinate = mitk::ToFProcessingCommon::IndexToCartesianCoordinates(i,j,distance,focalLengthX,focalLengthY,principalPoint[0],principalPoint[1]); expectedResult->InsertPoint(counter,coordinate); counter++; } } filter->Update(); mitk::PointSet::Pointer result = filter->GetOutput(); MITK_TEST_CONDITION_REQUIRED((expectedResult->GetSize()==result->GetSize()),"Test if point set size is equal"); MITK_TEST_CONDITION_REQUIRED(mitk::ToFTestingCommon::PointSetsEqual(expectedResult,result),"Testing filter without subset"); // compare filter result with ToFDistanceImageToSurfaceFilter MITK_INFO<<"Compare filter result with ToFDistanceImageToSurfaceFilter"; mitk::ToFDistanceImageToSurfaceFilter::Pointer surfaceFilter = mitk::ToFDistanceImageToSurfaceFilter::New(); surfaceFilter->SetInput(image); surfaceFilter->SetInterPixelDistance(interPixelDistance); surfaceFilter->SetCameraIntrinsics(cameraIntrinsics); surfaceFilter->SetReconstructionMode(mitk::ToFDistanceImageToSurfaceFilter::WithOutInterPixelDistance); MITK_TEST_CONDITION_REQUIRED(filter->GetReconstructionMode() == mitk::ToFDistanceImageToSurfaceFilter::WithOutInterPixelDistance,"Testing Set/GetReconstructionMode()"); mitk::Surface::Pointer surface = surfaceFilter->GetOutput(); surface->Update(); // create point set from surface mitk::PointSet::Pointer pointSet = mitk::ToFTestingCommon::VtkPolyDataToMitkPointSet(surface->GetVtkPolyData()); //compare pointset against ground truth MITK_TEST_CONDITION_REQUIRED((pointSet->GetSize()==result->GetSize()),"Test if point set size is equal"); MITK_TEST_CONDITION_REQUIRED(mitk::ToFTestingCommon::PointSetsEqual(pointSet,result),"Compare with surface points"); // test filter without subset (with using the interpixeldistance) MITK_INFO<<"Test filter without subset with using the interpixeldistance"; filter->Modified(); filter->SetReconstructionMode(false); expectedResult = mitk::PointSet::New(); counter = 0; for (unsigned int j=0; j index; index[0] = i; index[1] = j; mitk::ScalarType distance = imageAcces.GetPixelByIndex(index); mitk::Point3D coordinate = mitk::ToFProcessingCommon::IndexToCartesianCoordinatesWithInterpixdist(i,j,distance,focalLength,interPixelDistance,principalPoint); expectedResult->InsertPoint(counter,coordinate); counter++; } } filter->Update(); result = filter->GetOutput(); MITK_TEST_CONDITION_REQUIRED((expectedResult->GetSize()==result->GetSize()),"Test if point set size is equal"); MITK_TEST_CONDITION_REQUIRED(mitk::ToFTestingCommon::PointSetsEqual(expectedResult,result),"Testing filter without subset"); // compare filter result with ToFDistanceImageToSurfaceFilter MITK_INFO<<"Compare filter result with ToFDistanceImageToSurfaceFilter"; surfaceFilter = mitk::ToFDistanceImageToSurfaceFilter::New(); surfaceFilter->SetInput(image); surfaceFilter->SetInterPixelDistance(interPixelDistance); surfaceFilter->SetCameraIntrinsics(cameraIntrinsics); surfaceFilter->SetReconstructionMode(mitk::ToFDistanceImageToSurfaceFilter::WithInterPixelDistance); MITK_TEST_CONDITION_REQUIRED(surfaceFilter->GetReconstructionMode() == mitk::ToFDistanceImageToSurfaceFilter::WithInterPixelDistance,"Testing Set/GetReconstructionMode()"); surface = surfaceFilter->GetOutput(); surface->Update(); // create point set from surface pointSet = mitk::ToFTestingCommon::VtkPolyDataToMitkPointSet(surface->GetVtkPolyData()); //compare against ground truth MITK_TEST_CONDITION_REQUIRED((pointSet->GetSize()==result->GetSize()),"Test if point set size is equal"); MITK_TEST_CONDITION_REQUIRED(mitk::ToFTestingCommon::PointSetsEqual(pointSet,result),"Compare with surface points"); // test filter with subset (without using the interpixeldistance) MITK_INFO<<"Test filter with subset without using the interpixeldistance"; filter = mitk::ToFDistanceImageToPointSetFilter::New(); filter->SetInput(image); filter->SetInterPixelDistance(interPixelDistance); filter->SetCameraIntrinsics(cameraIntrinsics); filter->SetReconstructionMode(true); expectedResult = mitk::PointSet::New(); counter = 0; for(int i=0; iGetSize(); i++) { mitk::Point3D point = subSet->GetPoint(i); itk::Index<2> index; index[0] = point[0]; index[1] = point[1]; mitk::ScalarType distance = imageAcces.GetPixelByIndex(index); mitk::Point3D coordinate = mitk::ToFProcessingCommon::IndexToCartesianCoordinates(point[0],point[1], distance,focalLengthX,focalLengthY,principalPoint[0],principalPoint[1]); expectedResult->InsertPoint(counter,coordinate); counter++; } filter->SetSubset(subSet); filter->Modified(); filter->Update(); result = filter->GetOutput(); MITK_TEST_CONDITION_REQUIRED((expectedResult->GetSize()==result->GetSize()),"Test if point set size is equal"); MITK_TEST_CONDITION_REQUIRED(mitk::ToFTestingCommon::PointSetsEqual(expectedResult,result),"Testing filter with subset"); // test filter with subset (with using the interpixeldistance) MITK_INFO<<"Test filter with subset with using the interpixeldistance"; filter = mitk::ToFDistanceImageToPointSetFilter::New(); filter->SetInput(image); filter->SetInterPixelDistance(interPixelDistance); filter->SetCameraIntrinsics(cameraIntrinsics); filter->SetReconstructionMode(false); expectedResult = mitk::PointSet::New(); counter = 0; for(int i=0; iGetSize(); i++) { mitk::Point3D point = subSet->GetPoint(i); itk::Index<2> index; index[0] = point[0]; index[1] = point[1]; mitk::ScalarType distance = imageAcces.GetPixelByIndex(index); mitk::Point3D coordinate = mitk::ToFProcessingCommon::IndexToCartesianCoordinatesWithInterpixdist(point[0],point[1], distance,focalLength,interPixelDistance,principalPoint); expectedResult->InsertPoint(counter,coordinate); counter++; } filter->SetSubset(subSet); filter->Modified(); filter->Update(); result = filter->GetOutput(); MITK_TEST_CONDITION_REQUIRED((expectedResult->GetSize()==result->GetSize()),"Test if point set size is equal"); MITK_TEST_CONDITION_REQUIRED(mitk::ToFTestingCommon::PointSetsEqual(expectedResult,result),"Testing filter with subset"); MITK_TEST_END(); } diff --git a/Modules/ToFProcessing/Testing/mitkToFDistanceImageToSurfaceFilterTest.cpp b/Modules/ToFProcessing/Testing/mitkToFDistanceImageToSurfaceFilterTest.cpp index 2d56b24d90..365d1fc932 100644 --- a/Modules/ToFProcessing/Testing/mitkToFDistanceImageToSurfaceFilterTest.cpp +++ b/Modules/ToFProcessing/Testing/mitkToFDistanceImageToSurfaceFilterTest.cpp @@ -1,392 +1,392 @@ /*=================================================================== 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 #include #include #include #include #include #include -#include +#include #include #include #include #include #include /** * @brief Test for the class "ToFDistanceImageToSurfaceFilter". */ typedef mitk::ToFProcessingCommon::ToFPoint2D ToFPoint2D; typedef mitk::ToFProcessingCommon::ToFPoint3D ToFPoint3D; typedef mitk::ToFProcessingCommon::ToFScalarType ToFScalarType; int mitkToFDistanceImageToSurfaceFilterTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("ToFDistanceImageToSurfaceFilter"); mitk::ToFDistanceImageToSurfaceFilter::Pointer filter = mitk::ToFDistanceImageToSurfaceFilter::New(); // create test image unsigned int dimX =204; unsigned int dimY =204; mitk::Image::Pointer image = mitk::ImageGenerator::GenerateRandomImage(dimX,dimY); //initialize intrinsic parameters with some arbitrary values ToFScalarType focalLengthX = 295.78960; ToFScalarType focalLengthY = 296.348535; ToFPoint2D focalLengthXY; focalLengthXY[0]=focalLengthX; focalLengthXY[1]=focalLengthY; ToFScalarType k1=-0.36,k2=-0.14,p1=0.001,p2=-0.00; ToFPoint2D principalPoint; principalPoint[0] = 103.576546; principalPoint[1] = 100.1532; mitk::CameraIntrinsics::Pointer cameraIntrinsics = mitk::CameraIntrinsics::New(); cameraIntrinsics->SetFocalLength(focalLengthX,focalLengthY); cameraIntrinsics->SetPrincipalPoint(principalPoint[0],principalPoint[1]); cameraIntrinsics->SetDistorsionCoeffs(k1,k2,p1,p2); // test SetCameraIntrinsics() filter->SetCameraIntrinsics(cameraIntrinsics); MITK_TEST_CONDITION_REQUIRED((focalLengthX==filter->GetCameraIntrinsics()->GetFocalLengthX()),"Testing SetCameraIntrinsics with focalLength"); ToFPoint2D pp; pp[0] = filter->GetCameraIntrinsics()->GetPrincipalPointX(); pp[1] = filter->GetCameraIntrinsics()->GetPrincipalPointY(); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(principalPoint,pp),"Testing SetCameraIntrinsics with principalPoint()"); // test SetInterPixelDistance() ToFPoint2D interPixelDistance; interPixelDistance[0] = 0.04564; interPixelDistance[1] = 0.0451564; filter->SetInterPixelDistance(interPixelDistance); ToFPoint2D ipD = filter->GetInterPixelDistance(); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(ipD,interPixelDistance),"Testing Set/GetInterPixelDistance()"); // test SetReconstructionMode() filter->SetReconstructionMode(mitk::ToFDistanceImageToSurfaceFilter::WithInterPixelDistance); MITK_TEST_CONDITION_REQUIRED(filter->GetReconstructionMode() == mitk::ToFDistanceImageToSurfaceFilter::WithInterPixelDistance,"Testing Set/GetReconstructionMode()"); // test Set/GetInput() filter->SetInput(image); MITK_TEST_CONDITION_REQUIRED((image==filter->GetInput()),"Testing Set/GetInput()"); // test filter without subset (without interpixeldistance) MITK_INFO<<"Test filter with subset without interpixeldistance "; filter->SetReconstructionMode(mitk::ToFDistanceImageToSurfaceFilter::WithOutInterPixelDistance); MITK_TEST_CONDITION_REQUIRED(filter->GetReconstructionMode() == mitk::ToFDistanceImageToSurfaceFilter::WithOutInterPixelDistance,"Testing Set/GetReconstructionMode()"); vtkSmartPointer expectedResult = vtkSmartPointer::New(); expectedResult->SetDataTypeToDouble(); unsigned int counter = 0; double* point = new double[3]; // MITK_INFO<<"Test"; // MITK_INFO<<"focal: "< index = {{ i, j }}; float distance = 0.0; try { mitk::ImagePixelReadAccessor readAccess(image, image->GetSliceData()); distance = readAccess.GetPixelByIndex(index); } catch(mitk::Exception& e) { MITK_ERROR << "Image read exception!" << e.what(); } ToFPoint3D coordinate = mitk::ToFProcessingCommon::IndexToCartesianCoordinates(i,j,distance,focalLengthX,focalLengthY,principalPoint[0],principalPoint[1]); // if ((i==0)&&(j==0)) // { // MITK_INFO<<"Distance test: "<InsertPoint(pointID,point); } counter++; } } filter->Update(); mitk::Surface::Pointer resultSurface = filter->GetOutput(); vtkSmartPointer result = vtkSmartPointer::New(); result->SetDataTypeToDouble(); result = resultSurface->GetVtkPolyData()->GetPoints(); MITK_TEST_CONDITION_REQUIRED((expectedResult->GetNumberOfPoints()==result->GetNumberOfPoints()),"Test if number of points in surface is equal"); bool pointSetsEqual = true; for (unsigned int i=0; iGetNumberOfPoints(); i++) { double* expected = expectedResult->GetPoint(i); double* res = result->GetPoint(i); ToFPoint3D expectedPoint; expectedPoint[0] = expected[0]; expectedPoint[1] = expected[1]; expectedPoint[2] = expected[2]; ToFPoint3D resultPoint; resultPoint[0] = res[0]; resultPoint[1] = res[1]; resultPoint[2] = res[2]; if (!mitk::Equal(expectedPoint,resultPoint)) { // MITK_INFO << i; pointSetsEqual = false; } } MITK_TEST_CONDITION_REQUIRED(pointSetsEqual,"Testing filter without subset"); // test filter without subset (with interpixeldistance) MITK_INFO<<"Test filter with subset with interpixeldistance "; filter->SetReconstructionMode(mitk::ToFDistanceImageToSurfaceFilter::WithInterPixelDistance); MITK_TEST_CONDITION_REQUIRED(filter->GetReconstructionMode() == mitk::ToFDistanceImageToSurfaceFilter::WithInterPixelDistance,"Testing Set/GetReconstructionMode()"); // calculate focal length considering inter pixel distance ToFScalarType focalLength = (focalLengthX*interPixelDistance[0]+focalLengthY*interPixelDistance[1])/2.0; expectedResult = vtkSmartPointer::New(); expectedResult->SetDataTypeToDouble(); counter = 0; point = new double[3]; // MITK_INFO<<"Test"; // MITK_INFO<<"focal: "< index = {{ i, j }}; float distance = 0.0; try { mitk::ImagePixelReadAccessor readAccess(image, image->GetSliceData()); distance = readAccess.GetPixelByIndex(index); } catch(mitk::Exception& e) { MITK_ERROR << "Image read exception!" << e.what(); } ToFPoint3D coordinate = mitk::ToFProcessingCommon::IndexToCartesianCoordinatesWithInterpixdist(i,j,distance,focalLength,interPixelDistance,principalPoint); // if ((i==0)&&(j==0)) // { // MITK_INFO<<"Distance test: "<InsertPoint(pointID,point); } counter++; } } filter->Modified(); filter->Update(); resultSurface = filter->GetOutput(); result = vtkSmartPointer::New(); result->SetDataTypeToDouble(); result = resultSurface->GetVtkPolyData()->GetPoints(); MITK_TEST_CONDITION_REQUIRED((expectedResult->GetNumberOfPoints()==result->GetNumberOfPoints()),"Test if number of points in surface is equal"); pointSetsEqual = true; for (unsigned int i=0; iGetNumberOfPoints(); i++) { double* expected = expectedResult->GetPoint(i); double* res = result->GetPoint(i); ToFPoint3D expectedPoint; expectedPoint[0] = expected[0]; expectedPoint[1] = expected[1]; expectedPoint[2] = expected[2]; ToFPoint3D resultPoint; resultPoint[0] = res[0]; resultPoint[1] = res[1]; resultPoint[2] = res[2]; if (!mitk::Equal(expectedPoint,resultPoint)) { // MITK_INFO << i; MITK_INFO<<"expected: "<GetNumberOfPoints(); i++) { double* expected = expectedResult->GetPoint(i); double* res = result->GetPoint(i); ToFPoint3D expectedPoint; expectedPoint[0] = expected[0]; expectedPoint[1] = expected[1]; expectedPoint[2] = expected[2]; ToFPoint3D resultPoint; resultPoint[0] = res[0]; resultPoint[1] = res[1]; resultPoint[2] = res[2]; ToFPoint3D expectedPointBackward = mitk::ToFProcessingCommon::CartesianToIndexCoordinates(expectedPoint,focalLengthXY,principalPoint); ToFPoint3D resultPointBackward = mitk::ToFProcessingCommon::CartesianToIndexCoordinates(resultPoint,focalLengthXY,principalPoint); if (!mitk::Equal(expectedPointBackward,resultPointBackward)) { // MITK_INFO << i; // MITK_INFO<<"expected: "<GetNumberOfPoints(); i++) { double* expected = expectedResult->GetPoint(i); double* res = result->GetPoint(i); ToFPoint3D expectedPoint; expectedPoint[0] = expected[0]; expectedPoint[1] = expected[1]; expectedPoint[2] = expected[2]; ToFPoint3D resultPoint; resultPoint[0] = res[0]; resultPoint[1] = res[1]; resultPoint[2] = res[2]; ToFPoint3D expectedPointBackward = mitk::ToFProcessingCommon::CartesianToIndexCoordinatesWithInterpixdist(expectedPoint,focalLength,interPixelDistance,principalPoint); ToFPoint3D resultPointBackward = mitk::ToFProcessingCommon::CartesianToIndexCoordinatesWithInterpixdist(resultPoint,focalLength,interPixelDistance,principalPoint); if (!mitk::Equal(expectedPointBackward,resultPointBackward)) { // MITK_INFO << i; // MITK_INFO<<"expected: "<GetNumberOfPoints(); i++) { double* res = result->GetPoint(i); ToFPoint3D resultPoint; resultPoint[0] = res[0]; resultPoint[1] = res[1]; resultPoint[2] = res[2]; ToFPoint3D resultPointBackward = mitk::ToFProcessingCommon::CartesianToIndexCoordinates(resultPoint,focalLengthXY,principalPoint); itk::Index<2> index = {{ (int) (resultPointBackward[0]+0.5), (int) (resultPointBackward[1]+0.5) }}; float distanceBackward = 0.0; try { mitk::ImagePixelReadAccessor readAccess(image, image->GetSliceData()); distanceBackward = readAccess.GetPixelByIndex(index); } catch(mitk::Exception& e) { MITK_ERROR << "Image read exception!" << e.what(); } if (!mitk::Equal(distanceBackward,resultPointBackward[2])) { // MITK_INFO<<"expected: "<< image->GetPixelValueByIndex(pixelIndex); // MITK_INFO<<"result: "<< resultPoint; compareToInput = false; } } MITK_TEST_CONDITION_REQUIRED(compareToInput,"Testing backward transformation compared to original image without interpixeldistance"); //Backwardtransformation test compare to original input with interpixeldistance compareToInput = true; for (unsigned int i=0; iGetNumberOfPoints(); i++) { double* res = result->GetPoint(i); ToFPoint3D resultPoint; resultPoint[0] = res[0]; resultPoint[1] = res[1]; resultPoint[2] = res[2]; ToFPoint3D resultPointBackward = mitk::ToFProcessingCommon::CartesianToIndexCoordinatesWithInterpixdist(resultPoint,focalLength,interPixelDistance,principalPoint); itk::Index<2> pixelIndex = {{ (int) (resultPointBackward[0]+0.5), (int) (resultPointBackward[1]+0.5) }}; float distanceBackward = 0.0; try { mitk::ImagePixelReadAccessor readAccess(image, image->GetSliceData()); distanceBackward = readAccess.GetPixelByIndex(pixelIndex); } catch(mitk::Exception& e) { MITK_ERROR << "Image read exception!" << e.what(); } if (!mitk::Equal(distanceBackward,resultPointBackward[2])) { // MITK_INFO<<"expected: "<< image->GetPixelValueByIndex(pixelIndex); // MITK_INFO<<"result: "<< resultPoint; compareToInput = false; } } MITK_TEST_CONDITION_REQUIRED(compareToInput,"Testing backward transformation compared to original image with interpixeldistance"); //clean up delete point; // expectedResult->Delete(); MITK_TEST_END(); } diff --git a/Modules/ToFProcessing/mitkToFProcessingCommon.h b/Modules/ToFProcessing/mitkToFProcessingCommon.h index 2a28c1e5a5..dd1bc95c4e 100644 --- a/Modules/ToFProcessing/mitkToFProcessingCommon.h +++ b/Modules/ToFProcessing/mitkToFProcessingCommon.h @@ -1,345 +1,345 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKTOFPROCESSINGCOMMON_H #define MITKTOFPROCESSINGCOMMON_H #include "mitkToFProcessingExports.h" #include -#include "mitkVector.h" +#include "mitkTypes.h" #include namespace mitk { /** * @brief Helper class providing functions which are useful for multiple usage * * Currently the following methods are provided: *
    *
  • Conversion from 2D image coordinates to 3D world coordinates (IndexToCartesianCoordinates()) *
  • Conversion from 3D world coordinates to 2D image coordinates (CartesianToIndexCoordinates()) *
* The coordinate conversion follows the model of a common pinhole camera where the origin of the camera * coordinate system (world coordinates) is at the pinhole * \image html ../Modules/ToFProcessing/Documentation/PinholeCameraModel.png * The definition of the image plane and its coordinate systems (pixel and mm) is depicted in the following image * \image html ../Modules/ToFProcessing/Documentation/ImagePlane.png * @ingroup ToFProcessing */ class mitkToFProcessing_EXPORT ToFProcessingCommon { public: typedef double ToFScalarType; typedef itk::Point ToFPoint2D; typedef itk::Point ToFPoint3D; typedef itk::Vector ToFVector2D; typedef itk::Vector ToFVector3D; /*! \brief Convert index based distances to cartesian coordinates \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLengthX focal length of optical system in pixel units in x-direction (mostly obtained from camera calibration) \param focalLengthY focal length of optical system in pixel units in y-direction (mostly obtained from camera calibration) \param principalPointX x coordinate of principal point on image plane in pixel \param principalPointY y coordinate of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ static ToFPoint3D IndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLengthX, ToFScalarType focalLengthY, ToFScalarType principalPointX, ToFScalarType principalPointY); /*! \brief Convert index based distances to cartesian coordinates \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLength focal length of optical system in pixel units (mostly obtained from camera calibration) \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ inline static ToFPoint3D IndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFPoint2D focalLength, ToFPoint2D principalPoint) { return IndexToCartesianCoordinates(i,j,distance,focalLength[0],focalLength[1],principalPoint[0],principalPoint[1]); } /*! \brief Convert index based distances to cartesian coordinates \param index index coordinates \param distance distance value at given index in mm \param focalLength focal length of optical system in pixel units (mostly obtained from camera calibration) \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ inline static ToFPoint3D IndexToCartesianCoordinates(mitk::Index3D index, ToFScalarType distance, ToFPoint2D focalLength, ToFPoint2D principalPoint) { return IndexToCartesianCoordinates(index[0],index[1],distance,focalLength[0],focalLength[1],principalPoint[0], principalPoint[1]); } /*! \brief Convenience method to convert index based distances to cartesian coordinates using array as input \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLength focal length of optical system in pixel units (mostly obtained from camera calibration) \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ inline static ToFPoint3D IndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLength[2], ToFScalarType principalPoint[2]) { return IndexToCartesianCoordinates(i,j,distance,focalLength[0],focalLength[1],principalPoint[0],principalPoint[1]); } /*! \brief Convert index based distances to cartesian coordinates \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistanceX distance in x direction between adjacent pixels in mm \param interPixelDistanceY distance in y direction between adjacent pixels in mm \param principalPointX x coordinate of principal point on image plane in pixel \param principalPointY y coordinate of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ static ToFPoint3D IndexToCartesianCoordinatesWithInterpixdist(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLength, ToFScalarType interPixelDistanceX, ToFScalarType interPixelDistanceY, ToFScalarType principalPointX, ToFScalarType principalPointY); /*! \brief Convert index based distances to cartesian coordinates \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistance distance between adjacent pixels in mm \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ inline static ToFPoint3D IndexToCartesianCoordinatesWithInterpixdist(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLength, ToFPoint2D interPixelDistance, ToFPoint2D principalPoint) { return IndexToCartesianCoordinatesWithInterpixdist(i,j,distance,focalLength,interPixelDistance[0],interPixelDistance[1],principalPoint[0],principalPoint[1]); } /*! \brief Convert index based distances to cartesian coordinates \param index index coordinates \param distance distance value at given index in mm \param focalLength focal length of optical system (mostly obtained from camera calibration) \param interPixelDistance distance between adjacent pixels in mm for x and y direction \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ inline static ToFPoint3D IndexToCartesianCoordinatesWithInterpixdist(mitk::Index3D index, ToFScalarType distance, ToFScalarType focalLength, ToFPoint2D interPixelDistance, ToFPoint2D principalPoint) { return IndexToCartesianCoordinatesWithInterpixdist(index[0],index[1],distance,focalLength,interPixelDistance[0], interPixelDistance[1],principalPoint[0], principalPoint[1]); } /*! \brief Convenience method to convert index based distances to cartesian coordinates using array as input \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistance distance between adjacent pixels in mm \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ inline static ToFPoint3D IndexToCartesianCoordinatesWithInterpixdist(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLength, ToFScalarType interPixelDistance[2], ToFScalarType principalPoint[2]) { return IndexToCartesianCoordinatesWithInterpixdist(i,j,distance,focalLength,interPixelDistance[0],interPixelDistance[1],principalPoint[0],principalPoint[1]); } /*! \brief Convert cartesian coordinates to index based distances \param cartesianPointX x coordinate of point (of a surface or point set) to convert in 3D coordinates \param cartesianPointY y coordinate of point (of a surface or point set) to convert in 3D coordinates \param cartesianPointZ z coordinate of point (of a surface or point set) to convert in 3D coordinates \param focalLengthX focal length of optical system in pixel units in x-direction (mostly obtained from camera calibration) \param focalLengthY focal length of optical system in pixel units in y-direction (mostly obtained from camera calibration) \param principalPointX x coordinate of principal point on image plane in pixel \param principalPointY y coordinate of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ static ToFPoint3D CartesianToIndexCoordinates(ToFScalarType cartesianPointX, ToFScalarType cartesianPointY,ToFScalarType cartesianPointZ, ToFScalarType focalLengthX, ToFScalarType focalLengthY, ToFScalarType principalPointX, ToFScalarType principalPointY, bool calculateDistance=true); /*! \brief Convenience method to convert cartesian coordinates to index based distances using arrays \param cartesianPoint point (of a surface or point set) to convert in 3D coordinates \param focalLength focal length of optical system in pixel units (mostly obtained from camera calibration) \param principalPoint coordinates of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ inline static ToFPoint3D CartesianToIndexCoordinates(ToFScalarType cartesianPoint[3], ToFScalarType focalLength[2], ToFScalarType principalPoint[2], bool calculateDistance=true) { return CartesianToIndexCoordinates(cartesianPoint[0],cartesianPoint[1],cartesianPoint[2],focalLength[0], focalLength[1], principalPoint[0],principalPoint[1],calculateDistance); } /*! \brief Convert cartesian coordinates to index based distances \param cartesianPoint point (of a surface or point set) to convert in 3D coordinates \param focalLength focal length of optical system in pixel units (mostly obtained from camera calibration) \param principalPoint coordinates of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ inline static ToFPoint3D CartesianToIndexCoordinates(ToFPoint3D cartesianPoint, ToFPoint2D focalLength, ToFPoint2D principalPoint, bool calculateDistance=true) { return CartesianToIndexCoordinates(cartesianPoint[0],cartesianPoint[1],cartesianPoint[2],focalLength[0], focalLength[1], principalPoint[0],principalPoint[1],calculateDistance); } /*! \brief Convert cartesian coordinates to index based distances \param cartesianPointX x coordinate of point (of a surface or point set) to convert in 3D coordinates \param cartesianPointY y coordinate of point (of a surface or point set) to convert in 3D coordinates \param cartesianPointZ z coordinate of point (of a surface or point set) to convert in 3D coordinates \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistanceX distance in x direction between adjacent pixels in mm \param interPixelDistanceY distance in y direction between adjacent pixels in mm \param principalPointX x coordinate of principal point on image plane in pixel \param principalPointY y coordinate of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ static ToFPoint3D CartesianToIndexCoordinatesWithInterpixdist(ToFScalarType cartesianPointX, ToFScalarType cartesianPointY,ToFScalarType cartesianPointZ, ToFScalarType focalLength, ToFScalarType interPixelDistanceX, ToFScalarType interPixelDistanceY, ToFScalarType principalPointX, ToFScalarType principalPointY, bool calculateDistance=true); /*! \brief Convenience method to convert cartesian coordinates to index based distances using arrays \param cartesianPoint point (of a surface or point set) to convert in 3D coordinates \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistance distance between adjacent pixels in mm for x and y direction \param principalPoint coordinates of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ inline static ToFPoint3D CartesianToIndexCoordinatesWithInterpixdist(ToFScalarType cartesianPoint[3], ToFScalarType focalLength, ToFScalarType interPixelDistance[2], ToFScalarType principalPoint[2], bool calculateDistance=true) { return CartesianToIndexCoordinatesWithInterpixdist(cartesianPoint[0],cartesianPoint[1],cartesianPoint[2],focalLength, interPixelDistance[0],interPixelDistance[1],principalPoint[0],principalPoint[1],calculateDistance); } /*! \brief Convert cartesian coordinates to index based distances \param cartesianPoint point (of a surface or point set) to convert in 3D coordinates \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistance distance between adjacent pixels in mm for x and y direction \param principalPoint coordinates of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ inline static ToFPoint3D CartesianToIndexCoordinatesWithInterpixdist(ToFPoint3D cartesianPoint, ToFScalarType focalLength, ToFPoint2D interPixelDistance, ToFPoint2D principalPoint, bool calculateDistance=true) { return CartesianToIndexCoordinatesWithInterpixdist(cartesianPoint[0],cartesianPoint[1],cartesianPoint[2],focalLength, interPixelDistance[0],interPixelDistance[1],principalPoint[0],principalPoint[1],calculateDistance); } /** \ingroup KinectReconstruction * @{ * * @brief KinectIndexToCartesianCoordinates Convert a pixel (i,j) with value d to a 3D world point. This conversion is meant for Kinect and slightly different then ToF reconstruction. See also "Hacking the Kinect" - Jeff Kramer, Matt Parker, Daniel Herrera C., Nicolas Burrus, Florian Echtler, Chapter 7, Part 1 "Moving from Depth Map to Point Cloud. * @param i Pixel index i. * @param j Pixel index j. * @param distance Distance value d in mm as obtained from OpenNI. * @param focalLengthX Focallength from calibration. * @param focalLengthY Focallength from calibration. * @param principalPointX Principal point from calibration. * @param principalPointY Principal point from calibration. * @return a ToFPoint3D. The point in world coordinates (mm). */ static ToFProcessingCommon::ToFPoint3D KinectIndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLengthX, ToFScalarType focalLengthY, ToFScalarType principalPointX, ToFScalarType principalPointY); inline static ToFPoint3D KinectIndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLength[2], ToFScalarType principalPoint[2]) { return KinectIndexToCartesianCoordinates(i,j,distance,focalLength[0],focalLength[1],principalPoint[0],principalPoint[1]); } inline static ToFPoint3D KinectIndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFPoint2D focalLength, ToFPoint2D principalPoint) { return KinectIndexToCartesianCoordinates(i,j,distance,focalLength[0],focalLength[1],principalPoint[0],principalPoint[1]); } inline static ToFPoint3D KinectIndexToCartesianCoordinates(mitk::Index3D index, ToFScalarType distance, ToFPoint2D focalLength, ToFPoint2D principalPoint) { return KinectIndexToCartesianCoordinates(index[0],index[1],distance,focalLength[0],focalLength[1],principalPoint[0], principalPoint[1]); } /** @}*/ /** \ingroup KinectReconstructionInverse * @{ * @brief CartesianCoordinatesToKinectIndexCoordinates Transform a 3D world point back to distance image pixel coordinates. * @param cartesianPointX x value of the cartesian point. * @param cartesianPointY y value of the cartesian point. * @param cartesianPointZ z value of the cartesian point. * @param focalLengthX x value of the focal length (from calibration). * @param focalLengthY y value of the focal length (from calibration). * @param principalPointX x value of the principal point (from calibration). * @param principalPointY y value of the principal point (from calibration). * @param calculateDistance Do you want to compute also the distance of the distance image? For Kinect, this value is always the same in cartesian and index coordinates. * @return A ToFPoint3D containing the pixel indices (i,j) in [0] and [1] and (optionally) the distance value in [2] (or just 0.0). */ static ToFPoint3D CartesianToKinectIndexCoordinates(ToFScalarType cartesianPointX, ToFScalarType cartesianPointY, ToFScalarType cartesianPointZ, ToFScalarType focalLengthX, ToFScalarType focalLengthY, ToFScalarType principalPointX, ToFScalarType principalPointY, bool calculateDistance=true); inline static ToFProcessingCommon::ToFPoint3D CartesianToKinectIndexCoordinates(ToFPoint3D cartesianPoint, ToFPoint2D focalLength, ToFPoint2D principalPoint, bool calculateDistance=true) { return CartesianToKinectIndexCoordinates( cartesianPoint[0], cartesianPoint[1], cartesianPoint[2], focalLength[0], focalLength[1], principalPoint[0], principalPoint[1], calculateDistance); } /** @}*/ /** * @brief ContinuousKinectIndexToCartesianCoordinates This method is escpially meant for reconstructing a Kinect point * with continuous index coordinates (i.e. not exactly a pixel position, but a point interpolated between two pixels). * The only difference to KinectIndexToCartesianCoordinates() is that ContinuousKinectIndexToCartesianCoordinates does not * cast to unsigned int for the index. * @param continuousIndex The continuous coordinates (e.g. 0.5; 0.5). * @param distance Distance value d in mm as obtained from OpenNI. * @param focalLengthX x value of the focal length (from calibration). * @param focalLengthY y value of the focal length (from calibration) * @param principalPointX x value of the principal point (from calibration). * @param principalPointY y value of the principal point (from calibration). * @return a ToFPoint3D. The point in world coordinates (mm). */ static ToFProcessingCommon::ToFPoint3D ContinuousKinectIndexToCartesianCoordinates(mitk::Point2D continuousIndex, ToFScalarType distance, ToFScalarType focalLengthX, ToFScalarType focalLengthY, ToFScalarType principalPointX, ToFScalarType principalPointY); /** \brief Calculates the horizontal view angle of the camera with the given intrinsics \param intrinsics intrinsic parameters of the camera \param dimX dimension of the image in horizontal direction angle = atan(principalPoint[0]/focalLength[0]) + atan((dimX-principalPoint[0]/focalLength[0])) **/ static ToFScalarType CalculateViewAngle(mitk::CameraIntrinsics::Pointer intrinsics, unsigned int dimX); }; } #endif diff --git a/Modules/ToFProcessing/mitkToFTestingCommon.h b/Modules/ToFProcessing/mitkToFTestingCommon.h index fa895679e1..772b355a62 100644 --- a/Modules/ToFProcessing/mitkToFTestingCommon.h +++ b/Modules/ToFProcessing/mitkToFTestingCommon.h @@ -1,102 +1,102 @@ /*=================================================================== 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. ===================================================================*/ #ifndef mitkToFTestingCOMMON_H #define mitkToFTestingCOMMON_H #include "mitkToFProcessingExports.h" -#include "mitkVector.h" +#include "mitkTypes.h" #include #include #include #include #include #include namespace mitk { class mitkToFProcessing_EXPORT ToFTestingCommon { public: /** * @brief PointSetsEqual Method two test if two point sets contain the same points. mitk::Equal is used for comparison of the points. * @param pointSet1 * @param pointSet2 * @return True if pointsets are equal. */ static bool PointSetsEqual(mitk::PointSet::Pointer pointSet1, mitk::PointSet::Pointer pointSet2) { bool pointSetsEqual = true; if (pointSet1->GetSize()==pointSet2->GetSize()) { for (int i=0; iGetSize(); i++) { mitk::Point3D expectedPoint = pointSet1->GetPoint(i); mitk::Point3D resultPoint = pointSet2->GetPoint(i); if (!mitk::Equal(expectedPoint,resultPoint)) { std::cout << std::endl; std::cout << std::setprecision(12) << "expected: " << expectedPoint; std::cout << std::endl; std::cout << std::setprecision(12) << "resultPoint: " << resultPoint; std::cout << std::endl; pointSetsEqual = false; } } } else { pointSetsEqual = false; } return pointSetsEqual; } /** * @brief VtkPolyDatasEqual Convenience method for comparing the points of two vtkPolyData (using PointSetsEqual). * @param poly1 * @param poly2 * @return True if polydatas are equal. */ static bool VtkPolyDatasEqual( vtkSmartPointer poly1, vtkSmartPointer poly2 ) { return PointSetsEqual(VtkPolyDataToMitkPointSet(poly1), VtkPolyDataToMitkPointSet(poly2)); } /** * @brief VtkPolyDataToMitkPointSet Converts a vtkPolyData into an mitkPointSet * @param poly Input polydata. * @return mitk::PointSet::Pointer The resulting point set. */ static mitk::PointSet::Pointer VtkPolyDataToMitkPointSet( vtkSmartPointer poly ) { mitk::PointSet::Pointer result = mitk::PointSet::New(); int numberOfPoints = poly->GetNumberOfPoints(); for (int i=0; iGetPoint(i); mitk::Point3D point; point[0] = currentPoint[0]; point[1] = currentPoint[1]; point[2] = currentPoint[2]; result->InsertPoint(i,point); } return result; } }; } #endif diff --git a/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.h b/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.h index 116fcc88a6..f0b31fcd03 100644 --- a/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.h +++ b/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.h @@ -1,191 +1,191 @@ /*=================================================================== 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. ===================================================================*/ #ifndef MITKIRENDERWINDOWPART_H #define MITKIRENDERWINDOWPART_H #include #include #include #include -#include +#include #include #include class QmitkRenderWindow; namespace mitk { struct IRenderingManager; class SliceNavigationController; /** * \ingroup org_mitk_gui_common * * \brief Interface for a MITK Workbench Part providing a render window. * * This interface allows generic access to Workbench parts which provide some * kind of render window. The interface is intended to be implemented by * subclasses of berry::IWorkbenchPart. Usually, the interface is implemented * by a Workbench editor. * * A IRenderWindowPart provides zero or more QmitkRenderWindow instances which can * be controlled via this interface. QmitkRenderWindow instances have an associated * \e id, which is implementation specific. However, implementations should consider * to use one of the following ids for certain QmitkRenderWindow instances to maximize * reusability (they are free to map multiple ids to one QmitkRenderWindow internally): *
    *
  • transversal (deprecated, use axial instead)
  • *
  • axial
  • *
  • sagittal
  • *
  • coronal
  • *
  • 3d
  • *
* * \see ILinkedRenderWindowPart * \see IRenderWindowPartListener * \see QmitkAbstractRenderEditor */ struct MITK_GUI_COMMON_PLUGIN IRenderWindowPart { static const QString DECORATION_BORDER; // = "border" static const QString DECORATION_LOGO; // = "logo" static const QString DECORATION_MENU; // = "menu" static const QString DECORATION_BACKGROUND; // = "background; virtual ~IRenderWindowPart(); /** * Get the currently active (focused) render window. * Focus handling is implementation specific. * * \return The active QmitkRenderWindow instance; NULL * if no render window is active. */ virtual QmitkRenderWindow* GetActiveQmitkRenderWindow() const = 0; /** * Get all render windows with their ids. * * \return A hash map mapping the render window id to the QmitkRenderWindow instance. */ virtual QHash GetQmitkRenderWindows() const = 0; /** * Get a render window with a specific id. * * \param id The render window id. * \return The QmitkRenderWindow instance for id */ virtual QmitkRenderWindow* GetQmitkRenderWindow(const QString& id) const = 0; /** * Get the rendering manager used by this render window part. * * \return The current IRenderingManager instance or NULL * if no rendering manager is used. */ virtual mitk::IRenderingManager* GetRenderingManager() const = 0; /** * Request an update of all render windows. * * \param requestType Specifies the type of render windows for which an update * will be requested. */ virtual void RequestUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL) = 0; /** * Force an immediate update of all render windows. * * \param requestType Specifies the type of render windows for which an immediate update * will be requested. */ virtual void ForceImmediateUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL) = 0; /** * Get the SliceNavigationController for controlling time positions. * * \return A SliceNavigationController if the render window supports this * operation; otherwise returns NULL. */ virtual mitk::SliceNavigationController* GetTimeNavigationController() const = 0; /** * Get the selected position in the render window with id id * or in the active render window if id is NULL. * * \param id The render window id. * \return The currently selected position in world coordinates. */ virtual mitk::Point3D GetSelectedPosition(const QString& id = QString()) const = 0; /** * Set the selected position in the render window with id id * or in the active render window if id is NULL. * * \param pos The position in world coordinates which should be selected. * \param id The render window id in which the selection should take place. */ virtual void SetSelectedPosition(const mitk::Point3D& pos, const QString& id = QString()) = 0; /** * Enable \e decorations like colored borders, menu widgets, logos, text annotations, etc. * * Decorations are implementation specific. A set of standardized decoration names is listed * in GetDecorations(). * * \param enable If true enable the decorations specified in decorations, * otherwise disable them. * \param decorations A list of decoration names. If empty, all supported decorations are affected. * * \see GetDecorations() */ virtual void EnableDecorations(bool enable, const QStringList& decorations = QStringList()) = 0; /** * Return if a specific decoration is enabled. * * \return true if the decoration is enabled, false if it is disabled * or unknown. * * \see GetDecorations() */ virtual bool IsDecorationEnabled(const QString& decoration) const = 0; /** * Get a list of supported decorations. * * The following decoration names are standardized and should not be used for other decoration types: *
    *
  • \e DECORATION_BORDER Any border decorations like colored rectangles, etc. *
  • \e DECORATION_MENU Menus associated with render windows *
  • \e DECORATION_BACKGROUND All kinds of backgrounds (patterns, gradients, etc.) except for solid colored backgrounds *
  • \e DECORATION_LOGO Any kind of logo overlayed on the rendered scene *
* * \return A list of supported decoration names. */ virtual QStringList GetDecorations() const = 0; }; } Q_DECLARE_INTERFACE(mitk::IRenderWindowPart, "org.mitk.ui.IRenderWindowPart") #endif // MITKIRENDERWINDOWPART_H