diff --git a/Modules/Bundles/org.mitk.gui.qt.igttrackinglab/src/internal/QmitkIGTTrackingLabView.cpp b/Modules/Bundles/org.mitk.gui.qt.igttrackinglab/src/internal/QmitkIGTTrackingLabView.cpp index 17f15a7af3..90f434d5a0 100644 --- a/Modules/Bundles/org.mitk.gui.qt.igttrackinglab/src/internal/QmitkIGTTrackingLabView.cpp +++ b/Modules/Bundles/org.mitk.gui.qt.igttrackinglab/src/internal/QmitkIGTTrackingLabView.cpp @@ -1,1056 +1,1040 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkIGTTrackingLabView.h" #include "QmitkStdMultiWidget.h" #include #include #include #include #include #include #include #include #include #include #include #include // Qt #include #include const std::string QmitkIGTTrackingLabView::VIEW_ID = "org.mitk.views.igttrackinglab"; QmitkIGTTrackingLabView::QmitkIGTTrackingLabView() : QmitkFunctionality() ,m_Source(NULL) ,m_FiducialRegistrationFilter(NULL) ,m_PermanentRegistrationFilter(NULL) ,m_Visualizer(NULL) ,m_VirtualView(NULL) ,m_PSRecordingPointSet(NULL) ,m_RegistrationTrackingFiducialsName("Tracking Fiducials") ,m_RegistrationImageFiducialsName("Image Fiducials") ,m_PointSetRecordingDataNodeName("Recorded Points") ,m_PointSetRecording(false) ,m_ImageFiducialsDataNode(NULL) ,m_TrackerFiducialsDataNode(NULL) +,m_PermanentRegistrationSourcePoints(NULL) { //[-1;0;0] for WOLF_6D bronchoscope m_DirectionOfProjectionVector[0]=0; m_DirectionOfProjectionVector[1]=0; m_DirectionOfProjectionVector[2]=-1;} QmitkIGTTrackingLabView::~QmitkIGTTrackingLabView() { } void QmitkIGTTrackingLabView::CreateQtPartControl( QWidget *parent ) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi( parent ); m_ToolBox = new QToolBox(parent); m_Controls.m_VBoxLayout->addWidget(m_ToolBox); this->CreateBundleWidgets( parent ); this->CreateConnections(); } void QmitkIGTTrackingLabView::CreateBundleWidgets( QWidget* parent ) { // configuration widget m_NDIConfigWidget = new QmitkNDIConfigurationWidget(parent); m_NDIConfigWidget->SetToolTypes(QStringList () << "Instrument" << "Fiducial" << "Skinmarker" << "Unknown" ); m_ToolBox->addItem(m_NDIConfigWidget, "Configuration"); // registration widget m_RegistrationWidget = new QmitkFiducialRegistrationWidget(parent); m_RegistrationWidget->HideStaticRegistrationRadioButton(true); m_RegistrationWidget->HideContinousRegistrationRadioButton(true); m_RegistrationWidget->HideUseICPRegistrationCheckbox(true); m_ToolBox->addItem(m_RegistrationWidget, "Initial Registration"); // permanent registration widget m_PermanentRegistrationToolSelectionWidget = new QmitkToolSelectionWidget(parent); m_PermanentRegistrationToolSelectionWidget->SetCheckboxtText("Use this tool for permanent registration"); m_ToolBox->addItem(m_PermanentRegistrationToolSelectionWidget, "Permanent Registration"); // pointset recording m_ToolBox->addItem(this->CreatePointSetRecordingWidget(parent), "PointSet Recording"); // virtual view m_VirtualViewToolSelectionWidget = new QmitkToolSelectionWidget(parent); m_VirtualViewToolSelectionWidget->SetCheckboxtText("Enable Virtual Camera"); m_ToolBox->addItem(m_VirtualViewToolSelectionWidget, "Virtual Camera"); // tracking status m_ToolStatusWidget = new QmitkToolTrackingStatusWidget( parent ); m_Controls.m_VBoxLayout->addWidget(m_ToolStatusWidget); // update timer m_RenderingTimerWidget = new QmitkUpdateTimerWidget( parent ); m_RenderingTimerWidget->SetPurposeLabelText(QString("Navigation")); m_RenderingTimerWidget->SetTimerInterval( 50 ); // set rendering timer at 20Hz (updating every 50msec) m_Controls.m_VBoxLayout->addWidget(m_RenderingTimerWidget); } void QmitkIGTTrackingLabView::CreateConnections() { connect( m_ToolBox, SIGNAL(currentChanged(int)), this, SLOT(OnToolBoxCurrentChanged(int)) ); - connect( m_NDIConfigWidget, SIGNAL(Connected()), m_RenderingTimerWidget, SLOT(EnableWidget()) ); + //connect( m_NDIConfigWidget, SIGNAL(Connected()), m_RenderingTimerWidget, SLOT(EnableWidget()) ); connect( m_NDIConfigWidget, SIGNAL(Disconnected()), this, SLOT(OnTrackerDisconnected()) ); connect( m_NDIConfigWidget, SIGNAL(Connected()), this, SLOT(OnSetupNavigation()) ); connect( m_NDIConfigWidget, SIGNAL(SignalToolNameChanged(int, QString)), this, SLOT(OnChangeToolName(int, QString)) ); connect( m_NDIConfigWidget, SIGNAL(SignalLoadTool(int, mitk::DataNode::Pointer)), this, SLOT(OnToolLoaded(int, mitk::DataNode::Pointer)) ); connect( m_NDIConfigWidget, SIGNAL(ToolsAdded(QStringList)), this, SLOT(OnToolsAdded(QStringList)) ); connect( m_NDIConfigWidget, SIGNAL(RepresentationChanged( int ,mitk::Surface::Pointer )), this, SLOT(ChangeToolRepresentation( int, mitk::Surface::Pointer ))); connect( m_RegistrationWidget, SIGNAL(AddedTrackingFiducial()), this, SLOT(OnAddRegistrationTrackingFiducial()) ); connect( m_RegistrationWidget, SIGNAL(PerformFiducialRegistration()), this, SLOT(OnRegisterFiducials()) ); connect( m_RenderingTimerWidget, SIGNAL(Started()), this, SLOT(OnStartNavigation()) ); connect( m_RenderingTimerWidget, SIGNAL(Stopped()), this, SLOT(OnStopNavigation()) ); - connect( m_VirtualViewToolSelectionWidget, SIGNAL(SelectedToolChanged(int)), this, SLOT(OnVirtualCameraChanged(int))); + connect( m_VirtualViewToolSelectionWidget, SIGNAL(SignalUseTool(int, bool)), this, SLOT(OnVirtualCamera(int, bool))); connect( m_PermanentRegistrationToolSelectionWidget, SIGNAL(SignalUseTool(int, bool)), this, SLOT(OnPermanentRegistration(int, bool)) ); } void QmitkIGTTrackingLabView::OnAddRegistrationTrackingFiducial() { mitk::DataStorage* ds = this->GetDefaultDataStorage(); // check if DataStorage available if(ds == NULL) throw std::invalid_argument("DataStorage is not available"); if (m_FiducialRegistrationFilter.IsNull()) { std::string message( "IGT Pipeline is not ready. Please 'Start Navigation' before adding points"); QMessageBox::warning(NULL, "Adding Fiducials not possible", message.c_str()); return; } if (m_FiducialRegistrationFilter->GetNumberOfOutputs() < 1 || m_FiducialRegistrationFilter->GetNumberOfInputs() < 1) { std::string message("There are no tracking instruments! Please add an instrument first!"); QMessageBox::warning(NULL, "Adding Fiducials not possible", message.c_str()); return; } if (m_FiducialRegistrationFilter->GetInput()->IsDataValid() == false) { std::string message("instrument can currently not be tracked. Please make sure that the instrument is visible to the tracker"); QMessageBox::warning(NULL, "Adding Fiducials not possible", message.c_str()); return; } mitk::NavigationData::Pointer nd = m_Source->GetOutput(0); if( nd.IsNull() || !nd->IsDataValid()) QMessageBox::warning( 0, "Invalid tracking data", "Navigation data is not available or invalid!", QMessageBox::Ok ); // in case the tracker fiducials datanode has been renamed or removed //if(trackerFiducialsPS.IsNull()) //{ // mitk::DataNode::Pointer trackerFiducialsDN = mitk::DataNode::New(); // trackerFiducialsDN->SetName(m_RegistrationTrackingFiducialsName); // trackerFiducialsPS = mitk::PointSet::New(); // trackerFiducialsDN->SetData(trackerFiducialsPS); // m_RegistrationWidget->SetTrackerFiducialsNode(trackerFiducialsDN); //} if(m_TrackerFiducialsDataNode.IsNotNull() && m_TrackerFiducialsDataNode->GetData() != NULL) { mitk::PointSet::Pointer ps = dynamic_cast(m_TrackerFiducialsDataNode->GetData()); ps->InsertPoint(ps->GetSize(), nd->GetPosition()); } else QMessageBox::warning(NULL, "IGTSurfaceTracker: Error", "Can not access Tracker Fiducials. Adding fiducial not possible!"); } void QmitkIGTTrackingLabView::OnSetupNavigation() { if(m_Source.IsNotNull()) if(m_Source->IsTracking()) return; mitk::DataStorage* ds = this->GetDefaultDataStorage(); if(ds == NULL) { QMessageBox::warning(NULL, "IGTSurfaceTracker: Error", "can not access DataStorage. Navigation not possible"); return; } // Building up the filter pipeline try { this->SetupIGTPipeline(); } catch(std::exception& e) { QMessageBox::warning(NULL, QString("IGTSurfaceTracker: Error"), QString("Error while building the IGT-Pipeline: %1").arg(e.what())); this->DestroyIGTPipeline(); // destroy the pipeline if building is incomplete return; } catch(...) { QMessageBox::warning(NULL, QString("IGTSurfaceTracker: Error"), QString("Error while building the IGT-Pipeline")); this->DestroyIGTPipeline(); return; } } void QmitkIGTTrackingLabView::SetupIGTPipeline() { mitk::DataStorage* ds = this->GetDefaultDataStorage(); // check if DataStorage is available if(ds == NULL) throw std::invalid_argument("DataStorage is not available"); mitk::TrackingDevice::Pointer tracker = m_NDIConfigWidget->GetTracker(); // get current tracker from configuration widget if(tracker.IsNull()) // check if tracker is valid throw std::invalid_argument("tracking device is NULL!"); m_Source = mitk::TrackingDeviceSource::New(); // create new source for the IGT-Pipeline m_Source->SetTrackingDevice(tracker); // set the found tracker from the configuration widget to the source this->InitializeFilters(); // initialize all needed filters if(m_NDIConfigWidget->GetTracker()->GetType() == mitk::NDIAurora) { for (unsigned int i=0; i < m_Source->GetNumberOfOutputs(); ++i) { m_FiducialRegistrationFilter->SetInput(i, m_Source->GetOutput(i)); // set input for registration filter m_Visualizer->SetInput(i, m_FiducialRegistrationFilter->GetOutput(i)); // set input for visualization filter } for(unsigned int i= 0; i < m_Visualizer->GetNumberOfOutputs(); ++i) { const char* toolName = tracker->GetTool(i)->GetToolName(); mitk::DataNode::Pointer representation = this->CreateInstrumentVisualization(this->GetDefaultDataStorage(), toolName); m_PSRecToolSelectionComboBox->addItem(QString(toolName)); m_PermanentRegistrationToolSelectionWidget->AddToolName(QString(toolName)); m_VirtualViewToolSelectionWidget->AddToolName(QString(toolName)); m_Visualizer->SetRepresentationObject(i, representation->GetData()); } + if(m_Source->GetTrackingDevice()->GetToolCount() > 0) + m_RenderingTimerWidget->setEnabled(true); + mitk::RenderingManager::GetInstance()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_ALL); this->GlobalReinit(); } // this->CreateInstrumentVisualization(ds, tracker);//create for each single connected ND a corresponding 3D representation } void QmitkIGTTrackingLabView::InitializeFilters() { //1. Fiducial Registration Filters m_FiducialRegistrationFilter = mitk::NavigationDataLandmarkTransformFilter::New(); // filter used for initial fiducial registration //2. Visualization Filter m_Visualizer = mitk::NavigationDataObjectVisualizationFilter::New(); // filter to display NavigationData m_PermanentRegistrationFilter = mitk::NavigationDataLandmarkTransformFilter::New(); //3. Virtual Camera m_VirtualView = mitk::CameraVisualization::New(); // filter to update the vtk camera according to the reference navigation data + m_VirtualView->SetRenderer(mitk::BaseRenderer::GetInstance(this->GetActiveStdMultiWidget()->mitkWidget4->GetRenderWindow())); + + mitk::Vector3D viewUpInToolCoordinatesVector; + viewUpInToolCoordinatesVector[0]=1; + viewUpInToolCoordinatesVector[1]=0; + viewUpInToolCoordinatesVector[2]=0; + + m_VirtualView->SetDirectionOfProjectionInToolCoordinates(m_DirectionOfProjectionVector); + m_VirtualView->SetFocalLength(5000.0); + m_VirtualView->SetViewUpInToolCoordinates(viewUpInToolCoordinatesVector); } void QmitkIGTTrackingLabView::OnRegisterFiducials( ) { /* filter pipeline can only be build, if source and visualization filters exist */ if (m_Source.IsNull() || m_Visualizer.IsNull() || m_FiducialRegistrationFilter.IsNull()) { QMessageBox::warning(NULL, "Registration not possible", "Navigation pipeline is not ready. Please (re)start the navigation"); return; } if (m_Source->IsTracking() == false) { QMessageBox::warning(NULL, "Registration not possible", "Registration only possible if navigation is running"); return; } /* retrieve fiducials from data storage */ mitk::DataStorage* ds = this->GetDefaultDataStorage(); mitk::PointSet::Pointer imageFiducials = dynamic_cast(m_ImageFiducialsDataNode->GetData()); mitk::PointSet::Pointer trackerFiducials = dynamic_cast(m_TrackerFiducialsDataNode->GetData()); //mitk::PointSet::Pointer imageFiducials = ds->GetNamedObject(m_RegistrationImageFiducialsName.c_str()); //mitk::PointSet::Pointer trackerFiducials = ds->GetNamedObject(m_RegistrationTrackingFiducialsName.c_str()); if (imageFiducials.IsNull() || trackerFiducials.IsNull()) { QMessageBox::warning(NULL, "Registration not possible", "Fiducial data objects not found. \n" "Please set 3 or more fiducials in the image and with the tracking system.\n\n" "Registration is not possible"); return; } unsigned int minFiducialCount = 3; // \Todo: move to view option if ((imageFiducials->GetSize() < minFiducialCount) || (trackerFiducials->GetSize() < minFiducialCount) || (imageFiducials->GetSize() != trackerFiducials->GetSize())) { QMessageBox::warning(NULL, "Registration not possible", QString("Not enough fiducial pairs found. At least %1 fiducial must " "exist for the image and the tracking system respectively.\n" "Currently, %2 fiducials exist for the image, %3 fiducials exist for the tracking system").arg(minFiducialCount).arg(imageFiducials->GetSize()).arg(trackerFiducials->GetSize())); return; } /* now we have two PointSets with enough points to perform a landmark based transform */ if ( m_RegistrationWidget->UseICPIsChecked() ) m_FiducialRegistrationFilter->UseICPInitializationOn(); else m_FiducialRegistrationFilter->UseICPInitializationOff(); m_FiducialRegistrationFilter->SetSourceLandmarks(trackerFiducials); m_FiducialRegistrationFilter->SetTargetLandmarks(imageFiducials); if (m_FiducialRegistrationFilter.IsNotNull() && m_FiducialRegistrationFilter->IsInitialized()) // update registration quality display { QString registrationQuality = QString("%0: FRE is %1mm (Std.Dev. %2), \n" "RMS error is %3mm,\n" "Minimum registration error (best fitting landmark) is %4mm,\n" "Maximum registration error (worst fitting landmark) is %5mm.") .arg("Fiducial Registration") .arg(m_FiducialRegistrationFilter->GetFRE(), 3, 'f', 3) .arg(m_FiducialRegistrationFilter->GetFREStdDev(), 3, 'f', 3) .arg(m_FiducialRegistrationFilter->GetRMSError(), 3, 'f', 3) .arg(m_FiducialRegistrationFilter->GetMinError(), 3, 'f', 3) .arg(m_FiducialRegistrationFilter->GetMaxError(), 3, 'f', 3); m_RegistrationWidget->SetQualityDisplayText(registrationQuality); } //trackerFiducials->Clear(); //this->GlobalReinit(); } void QmitkIGTTrackingLabView::OnTrackerDisconnected() { m_RenderingTimerWidget->DisableWidget(); this->DestroyInstrumentVisualization(this->GetDefaultDataStorage(), m_NDIConfigWidget->GetTracker()); } mitk::DataNode::Pointer QmitkIGTTrackingLabView::CreateInstrumentVisualization(mitk::DataStorage* ds, const char* toolName) { //const char* toolName = tracker->GetTool(i)->GetToolName(); mitk::DataNode::Pointer toolRepresentationNode; toolRepresentationNode = ds->GetNamedNode(toolName); // check if node with same name already exists if(toolRepresentationNode.IsNotNull()) ds->Remove(toolRepresentationNode); // remove old node with same name toolRepresentationNode = this->CreateConeRepresentation( toolName ); // m_Visualizer->SetRepresentationObject(i, toolRepresentationNode->GetData()); ds->Add(toolRepresentationNode); // adds node to data storage return toolRepresentationNode; } mitk::DataNode::Pointer QmitkIGTTrackingLabView::CreateConeRepresentation( const char* label ) { //new data mitk::Cone::Pointer activeToolData = mitk::Cone::New(); vtkConeSource* vtkData = vtkConeSource::New(); vtkData->SetRadius(7.5); vtkData->SetHeight(15.0); vtkData->SetDirection(m_DirectionOfProjectionVector[0],m_DirectionOfProjectionVector[1],m_DirectionOfProjectionVector[2]); - vtkData->SetCenter(0.0, 0.0, 0.0); + vtkData->SetCenter(0.0, 0.0, 7.5); vtkData->SetResolution(20); vtkData->CappingOn(); vtkData->Update(); activeToolData->SetVtkPolyData(vtkData->GetOutput()); vtkData->Delete(); //new node mitk::DataNode::Pointer coneNode = mitk::DataNode::New(); coneNode->SetData(activeToolData); coneNode->GetPropertyList()->SetProperty("name", mitk::StringProperty::New( label )); coneNode->GetPropertyList()->SetProperty("layer", mitk::IntProperty::New(0)); coneNode->GetPropertyList()->SetProperty("visible", mitk::BoolProperty::New(true)); coneNode->SetColor(1.0,0.0,0.0); coneNode->SetOpacity(0.85); coneNode->Modified(); return coneNode; } void QmitkIGTTrackingLabView::DestroyIGTPipeline() { if(m_Source.IsNotNull()) { m_Source->StopTracking(); m_Source->Disconnect(); m_Source = NULL; } m_FiducialRegistrationFilter = NULL; m_PermanentRegistrationFilter = NULL; m_Visualizer = NULL; m_VirtualView = NULL; } void QmitkIGTTrackingLabView::OnChangeToolName(int index, QString name) { if(m_Source.IsNull()) return; mitk::DataStorage* ds = this->GetDefaultDataStorage(); if(ds == NULL) { QMessageBox::warning(NULL,"DataStorage Access Error", "Could not access DataStorage. Tool Name can not be changed!"); return; } mitk::NavigationData::Pointer tempND = m_Source->GetOutput(index); if(tempND.IsNull()) return; const char* oldName = tempND->GetName(); mitk::DataNode::Pointer tempNode = ds->GetNamedNode(oldName); if(tempNode.IsNotNull()) { tempNode->SetName(name.toStdString().c_str()); tempND->SetName(name.toStdString().c_str()); } else QMessageBox::warning(NULL, "Rename Tool Error", "Couldn't find the corresponding tool for changing it's name!"); } void QmitkIGTTrackingLabView::OnToolLoaded(int index, mitk::DataNode::Pointer toolNode) { if(m_Source.IsNull() || m_Visualizer.IsNull()) return; mitk::DataStorage* ds = this->GetDefaultDataStorage(); if(ds == NULL) { QMessageBox::warning(NULL,"DataStorage Access Error", "Could not access DataStorage. Loaded tool representation can not be shown!"); return; } mitk::NavigationData::Pointer tempND = m_Source->GetOutput(index); if(tempND.IsNull()) return; // try to find DataNode for tool in DataStorage const char* toolName = tempND->GetName(); mitk::DataNode::Pointer tempNode = ds->GetNamedNode(toolName); if(tempNode.IsNull()) { tempNode = mitk::DataNode::New(); // create new node, if none was found ds->Add(tempNode); } tempNode->SetData(toolNode->GetData()); tempNode->SetName(toolNode->GetName()); m_PSRecToolSelectionComboBox->setItemText(index,toolNode->GetName().c_str()); m_VirtualViewToolSelectionWidget->ChangeToolName(index, QString(toolNode->GetName().c_str())); m_PermanentRegistrationToolSelectionWidget->ChangeToolName(index, QString(toolNode->GetName().c_str())); m_Visualizer->SetRepresentationObject(index, tempNode->GetData()); m_Visualizer->Update(); tempNode->Modified(); this->GlobalReinit(); } void QmitkIGTTrackingLabView::OnStartNavigation() { if(m_Source.IsNull()) { QMessageBox::warning(NULL, "IGTTrackingLab: Error", "can not access tracking source. Navigation not possible"); return; } if(!m_Source->IsTracking()) { m_Source->StartTracking(); try { m_RenderingTimerWidget->GetTimerInterval(); this->StartContinuousUpdate(); // start tracker with set interval for(unsigned int i = 0; i < m_Source->GetNumberOfOutputs(); i++) // add navigation data to bundle widgets { m_ToolStatusWidget->AddNavigationData(dynamic_cast(m_Source->GetOutputs().at(i).GetPointer())); } m_ToolStatusWidget->ShowStatusLabels(); // show status for every tool if ND is valid or not //m_IGTPlayerWidget->setEnabled(true); } catch(...) { //m_IGTPlayerWidget->setDisabled(true); this->StopContinuousUpdate(); this->DestroyIGTPipeline(); return; } + m_NDIConfigWidget->EnableAddToolsButton(false); } } void QmitkIGTTrackingLabView::StopContinuousUpdate() { if (this->m_RenderingTimerWidget->GetUpdateTimer() != NULL) { m_RenderingTimerWidget->StopTimer(); disconnect( (QTimer*) m_RenderingTimerWidget->GetUpdateTimer(), SIGNAL(timeout()), this, SLOT(RenderScene()) ); // disconnect timer from RenderScene() method } if(m_PointSetRecordPushButton) m_PointSetRecordPushButton->setDisabled(true); } void QmitkIGTTrackingLabView::RenderScene( ) { try { if (m_Visualizer.IsNull() || this->GetActiveStdMultiWidget() == NULL) return; try { if(m_Source.IsNotNull() && m_Source->IsTracking()) m_ToolStatusWidget->Refresh(); if(m_VirtualViewToolSelectionWidget->IsSelectedToolActivated()) { m_VirtualView->Update(); mitk::Point3D p = m_Visualizer->GetOutput(m_VirtualViewToolSelectionWidget->GetCurrentSelectedIndex())->GetPosition(); this->GetActiveStdMultiWidget()->MoveCrossToPosition(p); } if(m_PermanentRegistrationToolSelectionWidget->IsSelectedToolActivated() && m_PermanentRegistrationToolSelectionWidget->GetCurrentSelectedIndex() >= 0 ) { mitk::NavigationData::Pointer permRegTool = m_Source->GetOutput((unsigned int) m_PermanentRegistrationToolSelectionWidget->GetCurrentSelectedIndex()); m_PermanentRegistrationFilter->SetSourceLandmarks(this->GetVirtualPointSetFromPosition(permRegTool)); } if(m_PointSetRecording && m_PSRecordingPointSet.IsNotNull()) { int size = m_PSRecordingPointSet->GetSize(); mitk::NavigationData::Pointer nd= m_Visualizer->GetOutput(m_PSRecToolSelectionComboBox->currentIndex()); if(size > 0) { mitk::Point3D p = m_PSRecordingPointSet->GetPoint(size-1); if(p.EuclideanDistanceTo(nd->GetPosition()) > (double) m_PSRecordingSpinBox->value()) m_PSRecordingPointSet->InsertPoint(size, nd->GetPosition()); } else m_PSRecordingPointSet->InsertPoint(size, nd->GetPosition()); } } catch(std::exception& e) { MITK_WARN << "Exception during QmitkIGTTrackingLab::RenderScene():" << e.what() << "\n"; } //if(m_VirtualViewCheckBox->isChecked()) // mitk::RenderingManager::GetInstance()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_ALL); ////update all Widgets //else m_Visualizer->Update(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_ALL); } catch (std::exception& e) { MITK_WARN << "RenderAll exception: " << e.what() << "\n"; } catch (...) { MITK_WARN << "RenderAll unknown exception\n"; } } void QmitkIGTTrackingLabView::StartContinuousUpdate( ) { if (m_Source.IsNull() || m_Visualizer.IsNull() ) throw std::invalid_argument("Pipeline is not set up correctly"); if (m_RenderingTimerWidget->GetUpdateTimer() == NULL) return; else { connect( (QTimer*) m_RenderingTimerWidget->GetUpdateTimer(), SIGNAL(timeout()), this, SLOT(RenderScene()) ); // connect update timer to RenderScene() method } if(m_PointSetRecordPushButton) m_PointSetRecordPushButton->setEnabled(true); } void QmitkIGTTrackingLabView::OnStopNavigation() { if(m_Source.IsNull()) { QMessageBox::warning(NULL, "IGTSurfaceTracker: Error", "can not access tracking source. Navigation not possible"); return; } if(m_Source->IsTracking()) { m_Source->StopTracking(); this->StopContinuousUpdate(); m_ToolStatusWidget->RemoveStatusLabels(); + + m_NDIConfigWidget->EnableAddToolsButton(true); } } void QmitkIGTTrackingLabView::OnToolsAdded(QStringList toolsList) { if(m_Source.IsNull() || m_FiducialRegistrationFilter.IsNull() || m_Visualizer.IsNull()) return; m_Source->UpdateOutputInformation(); unsigned int nrOfOldOutputs = m_Visualizer->GetNumberOfOutputs(); for(unsigned int i = nrOfOldOutputs; i < m_Source->GetNumberOfOutputs(); ++i) { m_FiducialRegistrationFilter->SetInput(i, m_Source->GetOutput(i)); m_Visualizer->SetInput(i, m_FiducialRegistrationFilter->GetOutput(i)); } -///TODO - m_VirtualView->SetInput(m_FiducialRegistrationFilter->GetOutput(0)); // initialize with input from 0 - m_VirtualView->SetRenderer(mitk::BaseRenderer::GetInstance(this->GetActiveStdMultiWidget()->mitkWidget4->GetRenderWindow())); - - mitk::Vector3D viewUpInToolCoordinatesVector; - viewUpInToolCoordinatesVector[0]=1; - viewUpInToolCoordinatesVector[1]=0; - viewUpInToolCoordinatesVector[2]=0; - - m_VirtualView->SetDirectionOfProjectionInToolCoordinates(m_DirectionOfProjectionVector); - m_VirtualView->SetFocalLength(5000.0); - m_VirtualView->SetViewUpInToolCoordinates(viewUpInToolCoordinatesVector); - for(unsigned int j = nrOfOldOutputs; j < m_Visualizer->GetNumberOfOutputs(); ++j) { mitk::DataNode::Pointer representation = this->CreateInstrumentVisualization(this->GetDefaultDataStorage(), m_Source->GetTrackingDevice()->GetTool(j)->GetToolName()); m_PSRecToolSelectionComboBox->addItem(QString(m_Source->GetTrackingDevice()->GetTool(j)->GetToolName())); m_PermanentRegistrationToolSelectionWidget->AddToolName(QString(m_Source->GetTrackingDevice()->GetTool(j)->GetToolName())); m_VirtualViewToolSelectionWidget->AddToolName(QString(m_Source->GetTrackingDevice()->GetTool(j)->GetToolName())); m_Visualizer->SetRepresentationObject(j, representation->GetData()); } + if(m_Source->GetTrackingDevice()->GetToolCount() > 0) + m_RenderingTimerWidget->setEnabled(true); + mitk::RenderingManager::GetInstance()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_ALL); this->GlobalReinit(); //mitk::RenderingManager::GetInstance()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_ALL); } void QmitkIGTTrackingLabView::InitializeRegistration() { mitk::DataStorage* ds = this->GetDefaultDataStorage(); if( ds == NULL ) return; m_RegistrationWidget->SetMultiWidget(this->GetActiveStdMultiWidget()); // passing multiwidget to pointsetwidget if(m_ImageFiducialsDataNode.IsNull()) { m_ImageFiducialsDataNode = mitk::DataNode::New(); mitk::PointSet::Pointer ifPS = mitk::PointSet::New(); m_ImageFiducialsDataNode->SetData(ifPS); mitk::Color color; color.Set(1.0f, 0.0f, 0.0f); m_ImageFiducialsDataNode->SetName(m_RegistrationImageFiducialsName); m_ImageFiducialsDataNode->SetColor(color); m_ImageFiducialsDataNode->SetBoolProperty( "updateDataOnRender", false ); ds->Add(m_ImageFiducialsDataNode); } m_RegistrationWidget->SetMultiWidget(this->GetActiveStdMultiWidget()); m_RegistrationWidget->SetImageFiducialsNode(m_ImageFiducialsDataNode); if(m_TrackerFiducialsDataNode.IsNull()) { m_TrackerFiducialsDataNode = mitk::DataNode::New(); mitk::PointSet::Pointer tfPS = mitk::PointSet::New(); m_TrackerFiducialsDataNode->SetData(tfPS); mitk::Color color; color.Set(0.0f, 1.0f, 0.0f); m_TrackerFiducialsDataNode->SetName(m_RegistrationTrackingFiducialsName); m_TrackerFiducialsDataNode->SetColor(color); m_TrackerFiducialsDataNode->SetBoolProperty( "updateDataOnRender", false ); ds->Add(m_TrackerFiducialsDataNode); } m_RegistrationWidget->SetTrackerFiducialsNode(m_TrackerFiducialsDataNode); } void QmitkIGTTrackingLabView::OnToolBoxCurrentChanged(const int index) { switch (index) { case RegistrationWidget: this->InitializeRegistration(); break; default: break; } } mitk::DataNode::Pointer QmitkIGTTrackingLabView::CreateRegistrationFiducialsNode( const std::string& label, const mitk::Color& color) { mitk::DataNode::Pointer fiducialsNode = mitk::DataNode::New(); mitk::PointSet::Pointer fiducialsPointSet = mitk::PointSet::New(); fiducialsNode->SetData(fiducialsPointSet); fiducialsNode->SetName( label ); fiducialsNode->SetColor( color ); fiducialsNode->SetBoolProperty( "updateDataOnRender", false ); return fiducialsNode; } void QmitkIGTTrackingLabView::ChangeToolRepresentation( int toolID , mitk::Surface::Pointer surface ) { mitk::DataStorage* ds = this->GetDefaultDataStorage(); if(ds == NULL) { QMessageBox::warning(NULL, "IGTSurfaceTracker: Error", "Can not access DataStorage. Changing tool representation not possible!"); return; } mitk::TrackingDevice::Pointer tracker = m_NDIConfigWidget->GetTracker(); if(tracker.IsNull()) { QMessageBox::warning(NULL, "IGTSurfaceTracker: Error", "Can not access Tracker. Changing tool representation not possible!"); return; } try { const char* name = tracker->GetTool(toolID)->GetToolName(); // get tool name by id mitk::DataNode::Pointer toolNode = ds->GetNamedNode(name); if(toolNode.IsNull()) return; toolNode->SetData(surface); // change surface representation of node toolNode->SetColor(0.45,0.70,0.85); //light blue like old 5D sensors toolNode->Modified(); m_Visualizer->SetRepresentationObject( toolID, toolNode->GetData()); // updating node with changed surface back in visualizer mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } catch(std::exception& e) { QMessageBox::warning(NULL, QString("IGTSurfaceTracker: Error"), QString("Can not change tool representation!").arg(e.what())); return; } } QWidget* QmitkIGTTrackingLabView::CreatePointSetRecordingWidget(QWidget* parent) { QWidget* pointSetRecordingWidget = new QWidget(parent); m_PSRecToolSelectionComboBox = new QComboBox(pointSetRecordingWidget); m_PSRecordingSpinBox = new QSpinBox(pointSetRecordingWidget); QLabel* psRecordingEpsilonDistance = new QLabel("mm (point distance)", pointSetRecordingWidget); // the recording button m_PointSetRecordPushButton = new QPushButton("Start PointSet Recording", pointSetRecordingWidget); m_PointSetRecordPushButton->setDisabled(true); m_PointSetRecordPushButton->setIcon(QIcon(":/QmitkQmitkIGTTrackingLabView/start_rec.png")); m_PointSetRecordPushButton->setCheckable(true); connect( m_PointSetRecordPushButton, SIGNAL(toggled(bool)), this, SLOT(OnPointSetRecording(bool)) ); // distances spin m_PSRecordingSpinBox->setValue(1); m_PSRecordingSpinBox->setMinimum(1); m_PSRecordingSpinBox->setMaximum(20); QLabel* toolSelectLabel = new QLabel("Select tool for recording:", pointSetRecordingWidget); QGridLayout* layout = new QGridLayout(pointSetRecordingWidget); int row = 0; int col = 0; layout->addWidget(toolSelectLabel,row,col++,1,1,Qt::AlignRight); layout->addWidget(m_PSRecToolSelectionComboBox,row,col++,1,3,Qt::AlignLeft); col +=2; layout->addWidget(m_PSRecordingSpinBox,row,col++,1,1,Qt::AlignRight); layout->addWidget(psRecordingEpsilonDistance, row, col++,1,1,Qt::AlignLeft); row++; col=4; layout->addWidget(m_PointSetRecordPushButton,row,col++,1,2,Qt::AlignRight); - - - return pointSetRecordingWidget; } -/* -QWidget* QmitkIGTTrackingLabView::CreateVirtualViewWidget(QWidget* parent) -{ - QWidget* virtualViewWidget = new QWidget(parent); - m_VirtualViewToolSelectionComboBox = new QComboBox(virtualViewWidget); - connect(m_VirtualViewToolSelectionComboBox, SIGNAL(SelectedToolChanged(int)), this, SLOT(OnVirtualCameraChanged(int))); - - - QLabel* toolSelectLabel = new QLabel("Select tool for virtual camera:", virtualViewWidget); - - // the virtual view checkbox - m_VirtualViewCheckBox = new QCheckBox("Enable Virtual Camera", virtualViewWidget); - - QGridLayout* layout = new QGridLayout(virtualViewWidget); - - int row = 0; - int col = 0; - - layout->addWidget(toolSelectLabel,row,col++,1,1,Qt::AlignRight); - layout->addWidget(m_VirtualViewToolSelectionComboBox,row,col++,1,1,Qt::AlignLeft); - layout->addWidget(m_VirtualViewCheckBox,row,col++,1,2,Qt::AlignRight); - - return virtualViewWidget; -} -*/ - void QmitkIGTTrackingLabView::OnPointSetRecording(bool record) { mitk::DataStorage* ds = this->GetDefaultDataStorage(); if(ds == NULL) return; if(record) { mitk::DataNode::Pointer psRecND = ds->GetNamedNode(m_PointSetRecordingDataNodeName); if(m_PSRecordingPointSet.IsNull() || psRecND.IsNull()) { m_PSRecordingPointSet = NULL; m_PSRecordingPointSet = mitk::PointSet::New(); mitk::DataNode::Pointer dn = mitk::DataNode::New(); dn->SetName(m_PointSetRecordingDataNodeName); dn->SetColor(0.,1.,0.); dn->SetData(m_PSRecordingPointSet); ds->Add(dn); } else m_PSRecordingPointSet->Clear(); m_PointSetRecording = true; m_PointSetRecordPushButton->setText("Stop PointSet Recording"); m_PSRecToolSelectionComboBox->setDisabled(true); - //m_VirtualViewToolSelectionComboBox->setDisabled(true); } else { m_PointSetRecording = false; m_PointSetRecordPushButton->setText("Start PointSet Recording"); m_PSRecToolSelectionComboBox->setEnabled(true); - //m_VirtualViewToolSelectionComboBox->setEnabled(true); } } void QmitkIGTTrackingLabView::DestroyInstrumentVisualization(mitk::DataStorage* ds, mitk::TrackingDevice::Pointer tracker) { if(ds == NULL || tracker.IsNull()) return; for(int i=0; i < tracker->GetToolCount(); ++i) { mitk::DataNode::Pointer dn = ds->GetNamedNode(tracker->GetTool(i)->GetToolName()); if(dn.IsNotNull()) ds->Remove(dn); } } void QmitkIGTTrackingLabView::GlobalReinit() { // request global reiinit mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox", mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred); // calculate bounding geometry of these nodes mitk::TimeSlicedGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible"); // initialize the views to the bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(bounds); //global reinit end } -void QmitkIGTTrackingLabView::OnVirtualCameraChanged(int toolNr) +void QmitkIGTTrackingLabView::OnVirtualCamera(int toolNr, bool on) { if(m_VirtualView.IsNull() || m_FiducialRegistrationFilter.IsNull()) return; - m_VirtualView->SetInput(m_FiducialRegistrationFilter->GetOutput(toolNr)); + if(on) + m_VirtualView->SetInput(m_FiducialRegistrationFilter->GetOutput(toolNr)); } void QmitkIGTTrackingLabView::OnPermanentRegistration(int toolID, bool on) { + if (m_PermanentRegistrationFilter.IsNull() || m_FiducialRegistrationFilter.IsNull()) + return; + if(on) { + if(m_PermanentRegistrationSourcePoints.IsNull()) + m_PermanentRegistrationSourcePoints = mitk::PointSet::New(); + // interconnectiong permanent registration filter between tracking source and fiducial registration filter for(unsigned int i=0; i < m_Source->GetNumberOfOutputs(); ++i) { m_PermanentRegistrationFilter->SetInput(i,m_Source->GetOutput(i)); m_FiducialRegistrationFilter->SetInput(i,m_PermanentRegistrationFilter->GetOutput(i)); } mitk::NavigationData::Pointer nd = m_Source->GetOutput((unsigned int) toolID); m_PermanentRegistrationFilter->SetTargetLandmarks(this->GetVirtualPointSetFromPosition(nd)); } else { for(unsigned int i=0; i < m_FiducialRegistrationFilter->GetNumberOfOutputs(); ++i) m_FiducialRegistrationFilter->SetInput(i,m_Source->GetOutput()); } } mitk::PointSet::Pointer QmitkIGTTrackingLabView::GetVirtualPointSetFromPosition(mitk::NavigationData::Pointer navigationData) { - - mitk::PointSet::Pointer ps = mitk::PointSet::New(); - typedef itk::QuaternionRigidTransform QuaternionTransformType; mitk::NavigationData::PositionType pointA; mitk::NavigationData::PositionType pointB; mitk::NavigationData::PositionType pointC; + //initializing three points with position(0|0|0) pointA.Fill(0); pointB.Fill(0); pointC.Fill(0); + // changing position off all points in order to make them orthogonal pointA[0] = 1; pointB[1] = 1; pointC[2] = 1; QuaternionTransformType::Pointer quatTransform = QuaternionTransformType::New(); + // orientation of NavigationData from parameter mitk::NavigationData::OrientationType quatIn = navigationData->GetOrientation(); + // set orientation to quaternion transform vnl_quaternion const vnlQuatIn(quatIn.x(), quatIn.y(), quatIn.z(), quatIn.r()); quatTransform->SetRotation(vnlQuatIn); + // transform each point pointA = quatTransform->TransformPoint(pointA); pointB = quatTransform->TransformPoint(pointB); pointC = quatTransform->TransformPoint(pointC); - - + // add position data from NavigationData parameter to each point pointA[0] += navigationData->GetPosition()[0]; pointA[1] += navigationData->GetPosition()[1]; pointA[2] += navigationData->GetPosition()[2]; pointB[0] += navigationData->GetPosition()[0]; pointB[1] += navigationData->GetPosition()[1]; pointB[2] += navigationData->GetPosition()[2]; pointC[0] += navigationData->GetPosition()[0]; pointC[1] += navigationData->GetPosition()[1]; pointC[2] += navigationData->GetPosition()[2]; - - ps->InsertPoint(0,pointA); - ps->InsertPoint(1,pointB); - ps->InsertPoint(2,pointC); + // insert points in source points pointset for the permanent registration landmark transform + m_PermanentRegistrationSourcePoints->InsertPoint(0,pointA); + m_PermanentRegistrationSourcePoints->InsertPoint(1,pointB); + m_PermanentRegistrationSourcePoints->InsertPoint(2,pointC); - return ps; + return m_PermanentRegistrationSourcePoints; } diff --git a/Modules/Bundles/org.mitk.gui.qt.igttrackinglab/src/internal/QmitkIGTTrackingLabView.h b/Modules/Bundles/org.mitk.gui.qt.igttrackinglab/src/internal/QmitkIGTTrackingLabView.h index e81c798169..33392fe823 100644 --- a/Modules/Bundles/org.mitk.gui.qt.igttrackinglab/src/internal/QmitkIGTTrackingLabView.h +++ b/Modules/Bundles/org.mitk.gui.qt.igttrackinglab/src/internal/QmitkIGTTrackingLabView.h @@ -1,265 +1,268 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef QmitkIGTTrackingLabView_h #define QmitkIGTTrackingLabView_h #include #include #include "ui_QmitkIGTTrackingLabViewControls.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include class QmitkNDIConfigurationWidget; class QmitkFiducialRegistrationWidget; class QmitkUpdateTimerWidget; class QmitkToolSelectionWidget; class QmitkToolTrackingStatusWidget; /*! \brief QmitkIGTTrackingLabView \warning This class is not yet documented. Use "git blame" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup ${plugin_target}_internal */ class QmitkIGTTrackingLabView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; /** \brief default constructor */ QmitkIGTTrackingLabView(); /** \brief default destructor */ virtual ~QmitkIGTTrackingLabView(); virtual void CreateQtPartControl(QWidget *parent); protected slots: /** \brief This method adds a new fiducial to the tracker fiducials PointSet. */ void OnAddRegistrationTrackingFiducial(); /** \brief This method calls the fiducial registration. */ void OnRegisterFiducials(); /** \brief This method should be called if deconnecting the tracker. */ void OnTrackerDisconnected(); /** \brief This method sets up the navigation pipeline before tracking is started. */ void OnSetupNavigation(); /** \brief This method changes the name of a specific tool. */ void OnChangeToolName(int index, QString name); /** \brief This method creates the surface representation for a tool loaded from file. */ void OnToolLoaded(int index, mitk::DataNode::Pointer toolNode); /** \brief This method starts the navigation. */ void OnStartNavigation(); /** \brief This method stops the navigation. */ void OnStopNavigation(); /** \brief This method performs the visualisation of all NavigationDatas and performs the PointSet recording if activated. */ void RenderScene(); /** \brief This method should be called if new tools have been added to the tracking device. */ void OnToolsAdded(QStringList toolsList); /** \brief This method reacts on toolbox item changes. */ void OnToolBoxCurrentChanged(int index); /** \brief This method initializes the registration for the FiducialRegistrationWidget. */ void InitializeRegistration(); /** \brief This method reacts on tool surface changes. */ void ChangeToolRepresentation( int toolID , mitk::Surface::Pointer surface ); /** \brief This method starts the PointSet recording. */ void OnPointSetRecording(bool record); /** \brief This method activates the virtual camera. */ - void OnVirtualCameraChanged(int toolNr); - + void OnVirtualCamera(int toolNr, bool on); + /** + \brief This method activates the permanent registration based on one tool's position. + */ void OnPermanentRegistration(int toolID, bool on); protected: enum ToolBoxElement // enums for the different ToolBox item tabs. { NDIConfigurationWidget = 0, RegistrationWidget = 1, - PointSetRecording = 2, - VirtualCamera = 3 + PermanentRecording = 2, + PointSetRecording = 3, + VirtualCamera = 4 }; Ui::QmitkIGTTrackingLabViewControls m_Controls; /** \brief This method creates all widgets this bundle needs. */ void CreateBundleWidgets( QWidget* parent ); /** \brief This method creates the SIGNAL SLOT connections. */ void CreateConnections(); - /** \brief This method sets up the filter pipeline. */ void SetupIGTPipeline(); /** \brief This method initializes all needed filters. */ void InitializeFilters(); /** \brief This method destroys the filter pipeline. */ void DestroyIGTPipeline(); /** \brief This method starts the continuos update of the tracking device and the rendering. */ void StartContinuousUpdate(); /** \brief This method stops the continuos update of the tracking device and the rendering. */ void StopContinuousUpdate(); /** \brief This method creates a DataNode for fiducial PointSets. */ mitk::DataNode::Pointer CreateRegistrationFiducialsNode( const std::string& label, const mitk::Color& color); /** \brief This method creates the visualization for all connected instruments. */ mitk::DataNode::Pointer CreateInstrumentVisualization(mitk::DataStorage* ds, const char* toolName); // create 3D models for all connected tools /** \brief This method creates a DataNode of a 3D cone object. */ mitk::DataNode::Pointer CreateConeRepresentation(const char* label = ""); // create a 3D cone as representation for a tool /** \brief This method destroys the instrument visualization. */ void DestroyInstrumentVisualization(mitk::DataStorage* ds, mitk::TrackingDevice::Pointer tracker); /** \brief This method creates a widget with all input objects needed for the PointSet recording. */ QWidget* CreatePointSetRecordingWidget(QWidget* parent); + /** - \brief This method creates a widget with all input objects needed for the virtual camera view. + \brief This method returns a PointSet with three vritual points transformed from the position and orientation of the given NavigationData. This method is needed to calculate the source points for permanent registration from one tool's position. */ - // QWidget* CreateVirtualViewWidget(QWidget* parent); + mitk::PointSet::Pointer GetVirtualPointSetFromPosition(mitk::NavigationData::Pointer navigationData); mitk::TrackingDeviceSource::Pointer m_Source; ///< source that connects to the tracking device - mitk::NavigationDataLandmarkTransformFilter::Pointer m_FiducialRegistrationFilter; ///< this filter transforms from tracking coordinates into mitk world coordinates - mitk::NavigationDataLandmarkTransformFilter::Pointer m_PermanentRegistrationFilter; + mitk::NavigationDataLandmarkTransformFilter::Pointer m_PermanentRegistrationFilter; ///< this filter transforms from tracking coordinates into mitk world coordinates if needed it is interconnected before the FiducialEegistrationFilter mitk::NavigationDataObjectVisualizationFilter::Pointer m_Visualizer; ///< visualization filter mitk::CameraVisualization::Pointer m_VirtualView; ///< filter to update the vtk camera according to the reference navigation data mitk::Vector3D m_DirectionOfProjectionVector;///< vector for direction of projection of instruments - mitk::PointSet::Pointer GetVirtualPointSetFromPosition(mitk::NavigationData::Pointer navigationData); + private: QToolBox* m_ToolBox; QComboBox* m_PSRecToolSelectionComboBox; QSpinBox* m_PSRecordingSpinBox; QPushButton* m_PointSetRecordPushButton; mitk::PointSet::Pointer m_PSRecordingPointSet; QmitkNDIConfigurationWidget* m_NDIConfigWidget; // tracking device configuration widget QmitkFiducialRegistrationWidget* m_RegistrationWidget; // landmark registration widget QmitkUpdateTimerWidget* m_RenderingTimerWidget; // update timer widget for rendering and updating QmitkToolTrackingStatusWidget* m_ToolStatusWidget; // tracking status visualizer widget std::string m_RegistrationTrackingFiducialsName; std::string m_RegistrationImageFiducialsName; std::string m_PointSetRecordingDataNodeName; bool m_PointSetRecording; mitk::DataNode::Pointer m_ImageFiducialsDataNode; mitk::DataNode::Pointer m_TrackerFiducialsDataNode; QmitkToolSelectionWidget* m_PermanentRegistrationToolSelectionWidget; QmitkToolSelectionWidget* m_VirtualViewToolSelectionWidget; mitk::NavigationData::PositionType m_TargetPosition; mitk::NavigationData::OrientationType m_PermanentRegistrationInitialOrientation; + mitk::PointSet::Pointer m_PermanentRegistrationSourcePoints; /** \brief This method performs GlobalReinit() for the rendering widgets. */ void GlobalReinit(); }; #endif // QmitkIGTTrackingLabView_h diff --git a/Modules/IGTUI/Qmitk/QmitkNDIConfigurationWidget.cpp b/Modules/IGTUI/Qmitk/QmitkNDIConfigurationWidget.cpp index 24d1e6e209..b2c918b29a 100644 --- a/Modules/IGTUI/Qmitk/QmitkNDIConfigurationWidget.cpp +++ b/Modules/IGTUI/Qmitk/QmitkNDIConfigurationWidget.cpp @@ -1,883 +1,887 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-03-21 19:27:37 +0100 (Sa, 21 Mrz 2009) $ Version: $Revision: 16719 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkNDIConfigurationWidget.h" #include #include #include #include #include #include #include #include #include #include "QmitkCustomVariants.h" //#include #include "QmitkNDIToolDelegate.h" /* VIEW MANAGEMENT */ QmitkNDIConfigurationWidget::QmitkNDIConfigurationWidget(QWidget* parent) : QWidget(parent), m_Controls(NULL), m_Tracker(NULL), m_Source(NULL), m_Delegate(NULL), m_SROMCellDefaultText(""), m_RepresentatonCellDefaultText("") { this->CreateQtPartControl(this); } QmitkNDIConfigurationWidget::~QmitkNDIConfigurationWidget() { m_Controls = NULL; m_Tracker = NULL; m_Source = NULL; } void QmitkNDIConfigurationWidget::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkNDIConfigurationWidget; m_Controls->setupUi(parent); QStringList comPorts; #ifdef WIN32 comPorts << "COM1" << "COM2" << "COM3" << "COM4" << "COM5" << "COM6" << "COM7" << "COM8" << "COM9"; #else comPorts << "/dev/ttyS1" << "/dev/ttyS2" << "/dev/ttyS3" << "/dev/ttyS4" << "/dev/ttyS5" << "/dev/ttyUSB0" << "/dev/ttyUSB1" << "/dev/ttyUSB2" << "/dev/ttyUSB3"; #endif m_Controls->m_ComPortSelector->addItems(comPorts); m_Delegate = new QmitkNDIToolDelegate(m_Controls->m_ToolTable); m_Delegate->SetDataStorage(NULL); //needs to be set later using the setter methods m_Delegate->SetPredicate(NULL); m_Delegate->SetTypes(QStringList()); m_Controls->m_ToolTable->setItemDelegate(m_Delegate); this->CreateConnections(); this->HidePolarisOptionsGroupbox(true); this->HideAuroraOptionsGroupbox(true); } } void QmitkNDIConfigurationWidget::CreateConnections() { connect(m_Controls->m_Connect, SIGNAL(clicked()), this, SLOT(OnConnect())); connect(m_Controls->m_DiscoverToolsBtn, SIGNAL(clicked()), this, SLOT(OnDiscoverTools())); connect(m_Controls->m_AddToolBtn, SIGNAL(clicked()), this, SLOT(OnAddPassiveTool())); connect(m_Controls->m_DisoverDevicesBtn, SIGNAL(clicked()), this, SLOT(OnDiscoverDevices())); connect(m_Controls->m_ToolTable->model(), SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(UpdateTrackerFromToolTable(const QModelIndex &, const QModelIndex &))); connect(m_Controls->m_DisoverDevicesBtnInfo, SIGNAL(clicked()), this, SLOT(OnDisoverDevicesBtnInfo())); connect(m_Controls->m_SaveToolPushButton, SIGNAL(clicked()), this, SLOT(OnSaveTool()) ); connect(m_Controls->m_LoadToolPushButton, SIGNAL(clicked()), this, SLOT(OnLoadTool()) ); } void QmitkNDIConfigurationWidget::OnConnect() { if (m_Tracker.IsNotNull()) { m_Tracker->CloseConnection(); m_Tracker = NULL; } this->CreateTracker(); this->SetupTracker(); bool okay = m_Tracker->OpenConnection(); if (okay) { // show/hide options according to connected device if(m_Tracker->GetType() == mitk::NDIPolaris) { this->HideAuroraOptionsGroupbox(true); this->HidePolarisOptionsGroupbox(false); } else if(m_Tracker->GetType() == mitk::NDIAurora) { this->HidePolarisOptionsGroupbox(true); this->HideAuroraOptionsGroupbox(false); } this->UpdateWidgets(); this->UpdateToolTable(); connect(m_Controls->m_ToolTable, SIGNAL(cellChanged(int,int)), this, SLOT(OnTableCellChanged(int,int))); emit ToolsAdded(this->GetToolNamesList()); emit Connected(); } else { QMessageBox::warning(NULL, "Error", QString("Connection failed. Tracking device error message is '%1'").arg(m_Tracker->GetErrorMessage())); m_Tracker->CloseConnection(); this->m_Tracker = NULL; } } void QmitkNDIConfigurationWidget::OnDisconnect() { if (m_Tracker.IsNull()) return; m_Tracker->CloseConnection(); m_Tracker = NULL; disconnect(m_Controls->m_ToolTable, SIGNAL(cellChanged(int,int)), this, SLOT(OnTableCellChanged(int,int))); m_Controls->m_ToolSelectionComboBox->clear(); this->UpdateToolTable(); this->UpdateWidgets(); emit ToolsAdded(this->GetToolNamesList()); emit Disconnected(); this->HidePolarisOptionsGroupbox(true); this->HideAuroraOptionsGroupbox(true); } void QmitkNDIConfigurationWidget::UpdateWidgets() { m_Controls->m_DeviceStatus->setText(this->GetStatusText()); if (m_Tracker.IsNull()) // not connected to tracker { m_Controls->m_Connect->setText("Connect"); m_Controls->m_lConnection->setText("III. Enable connection to device "); disconnect(m_Controls->m_Connect, SIGNAL(clicked()), this, SLOT(OnDisconnect())); connect(m_Controls->m_Connect, SIGNAL(clicked()), this, SLOT(OnConnect())); m_Controls->m_DiscoverToolsBtn->setDisabled(true); m_Controls->m_AddToolBtn->setDisabled(true); return; } if (m_Tracker->GetState() == mitk::TrackingDevice::Setup) { m_Controls->m_Connect->setText("Connect"); m_Controls->m_lConnection->setText("III. Enable connection to device "); disconnect(m_Controls->m_Connect, SIGNAL(clicked()), this, SLOT(OnDisconnect())); connect(m_Controls->m_Connect, SIGNAL(clicked()), this, SLOT(OnConnect())); m_Controls->m_DiscoverToolsBtn->setDisabled(true); m_Controls->m_AddToolBtn->setDisabled(true); return; } if ((m_Tracker->GetState() == mitk::TrackingDevice::Ready) || (m_Tracker->GetState() == mitk::TrackingDevice::Tracking)) { m_Controls->m_Connect->setText("Disconnect"); m_Controls->m_lConnection->setText("III. Disable connection to device "); disconnect(m_Controls->m_Connect, SIGNAL(clicked()), this, SLOT(OnConnect())); connect(m_Controls->m_Connect, SIGNAL(clicked()), this, SLOT(OnDisconnect())); m_Controls->m_DiscoverToolsBtn->setEnabled(true); m_Controls->m_AddToolBtn->setEnabled(true); } } QString QmitkNDIConfigurationWidget::GetStatusText() { if (m_Tracker.IsNull()) return QString("Not connected"); QString devName; switch (m_Tracker->GetType()) { case mitk::NDIAurora: devName = "NDI Aurora"; break; case mitk::NDIPolaris: devName = "NDI Polaris"; break; case mitk::TrackingSystemNotSpecified: default: devName = "unknown tracking device"; break; } if (m_Tracker->GetState() == mitk::TrackingDevice::Ready) return QString("Connected to %1 on %2. Device is ready.").arg(devName).arg(m_Tracker->GetDeviceName()); if (m_Tracker->GetState() == mitk::TrackingDevice::Tracking) return QString("%1 is tracking.").arg(devName); return QString(""); } void QmitkNDIConfigurationWidget::OnDiscoverTools() { if (m_Tracker.IsNull()) { QMessageBox::warning(NULL, "Error", QString("Connection failed. No tracking device found.")); return; } m_Tracker->DiscoverWiredTools(); this->UpdateToolTable(); emit ToolsAdded(this->GetToolNamesList()); } void QmitkNDIConfigurationWidget::OnAddPassiveTool() { if (m_Tracker.IsNull()) this->CreateTracker(); QStringList filenames = QFileDialog::getOpenFileNames(this, "Select NDI SROM file", QDir::currentPath(),"NDI SROM files (*.rom)"); if (filenames.isEmpty()) { this->m_Tracker = NULL; return; } foreach(QString fileName, filenames) { //QString toolName = QInputDialog::getText(this, "Enter a name for the tool", "Name of the tool: ", QLineEdit::Normal, QFileInfo(filename).baseName(), &ok); //if (ok == false || toolName.isEmpty()) // return; m_Tracker->AddTool(QFileInfo(fileName).baseName().toLatin1(), fileName.toLatin1()); m_Tracker->Modified(); } emit ToolsAdded(this->GetToolNamesList()); this->UpdateToolTable(); } void QmitkNDIConfigurationWidget::CreateTracker() { m_Tracker = mitk::NDITrackingDevice::New(); } void QmitkNDIConfigurationWidget::SetupTracker() { if (m_Tracker.IsNull()) return; m_Tracker->SetDeviceName(this->GetDeviceName()); m_Tracker->SetBaudRate(mitk::SerialCommunication::BaudRate115200); } std::string QmitkNDIConfigurationWidget::GetDeviceName() const { if (m_Controls == NULL) return NULL; QString deviceName = m_Controls->m_ComPortSelector->currentText(); #if WIN32 deviceName.prepend("\\\\.\\"); // always prepend "\\.\ to all COM ports, to be able to connect to ports > 9" #endif return deviceName.toStdString(); } void QmitkNDIConfigurationWidget::SetDeviceName( const char* dev ) { if (m_Controls == NULL) return; m_Controls->m_ComPortSelector->setCurrentIndex(m_Controls->m_ComPortSelector->findText(dev)); } void QmitkNDIConfigurationWidget::UpdateToolTable() { //disconnect(m_Controls->m_ToolTable, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(OnTableItemChanged(QTableWidgetItem*))); // stop listening to table changes disconnect(m_Controls->m_ToolTable->model(), SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(UpdateTrackerFromToolTable(const QModelIndex &, const QModelIndex &))); disconnect(m_Controls->m_ToolTable, SIGNAL( clicked ( const QModelIndex & )), this, SLOT ( OnTableItemClicked( const QModelIndex & ))); m_Controls->m_ToolTable->clearContents(); m_Controls->m_ToolTable->setRowCount(0); if (m_Tracker.IsNull() || (m_Controls == NULL)) return; m_Controls->m_ToolSelectionComboBox->clear(); m_Controls->m_ToolTable->setRowCount(m_Tracker->GetToolCount()); for (unsigned int i = 0; i < m_Tracker->GetToolCount(); ++i) { mitk::TrackingTool* t = m_Tracker->GetTool(i); if (t == NULL) { m_Controls->m_ToolTable->setItem(i, QmitkNDIToolDelegate::IndexCol, new QTableWidgetItem("INVALID")); // Index continue; } m_Controls->m_ToolSelectionComboBox->addItem(m_Tracker->GetTool(i)->GetToolName()); m_Controls->m_ToolTable->setItem(i, QmitkNDIToolDelegate::IndexCol, new QTableWidgetItem(QString::number(i))); // Index m_Controls->m_ToolTable->setItem(i, QmitkNDIToolDelegate::NameCol, new QTableWidgetItem(t->GetToolName())); // Name if (dynamic_cast(t)->GetSROMDataLength() > 0) m_Controls->m_ToolTable->setItem(i, QmitkNDIToolDelegate::SROMCol, new QTableWidgetItem("SROM file loaded")); // SROM file else m_Controls->m_ToolTable->setItem(i, QmitkNDIToolDelegate::SROMCol, new QTableWidgetItem(m_SROMCellDefaultText)); // SROM file m_Controls->m_ToolTable->setItem(i, QmitkNDIToolDelegate::TypeCol, new QTableWidgetItem("")); // Type if (t->IsEnabled()) m_Controls->m_ToolTable->setItem(i, QmitkNDIToolDelegate::StatusCol, new QTableWidgetItem("Enabled")); // Status else m_Controls->m_ToolTable->setItem(i, QmitkNDIToolDelegate::StatusCol, new QTableWidgetItem("Disabled")); // Status m_Controls->m_ToolTable->setItem(i, QmitkNDIToolDelegate::NodeCol, new QTableWidgetItem("")); // Node m_Controls->m_ToolTable->setItem(i, QmitkNDIToolDelegate::RepCol, new QTableWidgetItem(m_RepresentatonCellDefaultText)); // Representation /* set read-only/editable flags */ m_Controls->m_ToolTable->item(i, QmitkNDIToolDelegate::IndexCol)->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled); // Index m_Controls->m_ToolTable->item(i, QmitkNDIToolDelegate::NodeCol)->setFlags(Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled); // Name m_Controls->m_ToolTable->item(i, QmitkNDIToolDelegate::SROMCol)->setFlags(Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled); // SROM file m_Controls->m_ToolTable->item(i, QmitkNDIToolDelegate::TypeCol)->setFlags(Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled); // Type m_Controls->m_ToolTable->item(i, QmitkNDIToolDelegate::StatusCol)->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled); // Status m_Controls->m_ToolTable->item(i, QmitkNDIToolDelegate::NodeCol)->setFlags(Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled); // Node m_Controls->m_ToolTable->item(i, QmitkNDIToolDelegate::RepCol)->setFlags(Qt::NoItemFlags); // Representation surface file } m_Controls->m_ToolTable->resizeColumnsToContents(); //connect(m_Controls->m_ToolTable, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(OnTableItemChanged(QTableWidgetItem*))); // listen to table changes again connect(m_Controls->m_ToolTable->model(), SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(UpdateTrackerFromToolTable(const QModelIndex &, const QModelIndex &))); connect(m_Controls->m_ToolTable, SIGNAL( clicked ( const QModelIndex & )), this, SLOT ( OnTableItemClicked( const QModelIndex & ))); } void QmitkNDIConfigurationWidget::OnDiscoverDevices() { PortDeviceMap portsAndDevices; QString status = "Scanning "; #ifdef WIN32 QString devName; for (unsigned int i = 1; i < 20; ++i) { if (i<10) devName = QString("COM%1").arg(i); else devName = QString("\\\\.\\COM%1").arg(i); // prepend "\\.\ to COM ports >9, to be able to allow connection" portsAndDevices[devName]; status += QString("COM%1").arg(i) + ", "; } #else //linux/posix systems for(unsigned int i = 1; i < 6; ++i) { QString devName = QString("/dev/ttyS%1").arg(i); portsAndDevices[devName]; status += devName + ", "; } for(unsigned int i = 0; i <7; ++i) { QString devName = QString("/dev/ttyUSB%1").arg(i); portsAndDevices[devName]; status += devName + ", "; } #endif status.chop(2); // remove last ", " status += " for NDI tracking devices..."; m_Controls->m_DeviceStatus->setText(status); ScanPortsForNDITrackingDevices(portsAndDevices); m_Controls->m_ComPortSelector->clear(); QString result = "The following tracking devices were found:
\n"; for (PortDeviceMap::const_iterator it = portsAndDevices.begin(); it != portsAndDevices.end(); ++it) { QString tmpComPort = it.key(); if (tmpComPort.startsWith("\\")) { tmpComPort.remove(0,4); // remove "\\.\" for nice ui visualisation } result += tmpComPort + ": "; switch (it.value()) { case mitk::NDIPolaris: result += "NDI Polaris
\n"; m_Controls->m_ComPortSelector->addItem(tmpComPort); break; case mitk::NDIAurora: result += "NDI Aurora
\n"; m_Controls->m_ComPortSelector->addItem(tmpComPort); break; default: result += "No NDI tracking device found
\n"; } } //QMessageBox::information(NULL, "Tracking Device Discovery", result); m_Controls->m_DeviceStatus->setText(result); } mitk::TrackingDeviceType QmitkNDIConfigurationWidget::ScanPort(QString port) { mitk::NDITrackingDevice::Pointer tracker = mitk::NDITrackingDevice::New(); tracker->SetDeviceName(port.toStdString()); return tracker->TestConnection(); } void QmitkNDIConfigurationWidget::ScanPortsForNDITrackingDevices( PortDeviceMap& portsAndDevices ) { // Iterative scanning: for (PortDeviceMap::iterator it = portsAndDevices.begin(); it != portsAndDevices.end(); ++it) it.value() = this->ScanPort(it.key()); // \Todo: use parallel scanning //QtConcurrent::blockingMap( portsAndDevices.begin(), portsAndDevices.end(), ScanPort ); //MITK_INFO << portsAndDevices; } QStringList QmitkNDIConfigurationWidget::GetToolNamesList() { QStringList toolNames; if (m_Tracker.IsNull()) return toolNames; for (unsigned int i = 0; i < m_Tracker->GetToolCount(); ++i) { mitk::TrackingTool* t = m_Tracker->GetTool(i); if (t == NULL) continue; toolNames << t->GetToolName(); } return toolNames; } mitk::NDITrackingDevice* QmitkNDIConfigurationWidget::GetTracker() const { return m_Tracker.GetPointer(); } void QmitkNDIConfigurationWidget::SetToolTypes(const QStringList& types) { m_Delegate->SetTypes(types); } void QmitkNDIConfigurationWidget::SetDataStorage(mitk::DataStorage* ds) { m_Delegate->SetDataStorage(ds); } void QmitkNDIConfigurationWidget::SetPredicate(mitk::NodePredicateBase::Pointer p) { m_Delegate->SetPredicate(p); } void QmitkNDIConfigurationWidget::SetTagPropertyName( const std::string& name ) { m_Delegate->SetTagPropertyName(name); } void QmitkNDIConfigurationWidget::SetTagProperty( mitk::BaseProperty::Pointer prop ) { m_Delegate->SetTagProperty(prop); } void QmitkNDIConfigurationWidget::OnTableItemClicked(const QModelIndex & topLeft ) { QString filename; QTableWidgetItem* filenameItem; switch (topLeft.column()) { case QmitkNDIToolDelegate::RepCol: filename = QFileDialog::getOpenFileName(this, "Select Surface File", QDir::currentPath(),"STL files (*.stl)"); filenameItem = new QTableWidgetItem(filename); m_Controls->m_ToolTable->setItem( topLeft.row(), topLeft.column(), filenameItem ); if(QFileInfo(filename).exists()) { mitk::Surface::Pointer surface = this->LoadSurfaceFromSTLFile(filename); if(surface.IsNotNull()) emit RepresentationChanged( topLeft.row(), surface); } break; default: break; } } void QmitkNDIConfigurationWidget::UpdateTrackerFromToolTable(const QModelIndex & topLeft, const QModelIndex & /*bottomRight*/) { //Colums ID doesn't have to be processed. if (topLeft.column()<1) return; if (m_Tracker.IsNull()) return; if (topLeft.row() >= (int) m_Tracker->GetToolCount()) return; QAbstractItemModel* model = m_Controls->m_ToolTable->model(); //define topleft contains row and column; row 0 is tool 0; column is index =0, Name =1, SROMFileName = 2; Type = 3; Status = 4; Node (?) = 5 //only update the changed item mitk::NDIPassiveTool* tool = dynamic_cast (m_Tracker->GetTool(topLeft.row())); if (tool == NULL) return; switch (topLeft.column()) { case QmitkNDIToolDelegate::IndexCol: //index break; case QmitkNDIToolDelegate::NameCol: //name tool->SetToolName(model->data(model->index(topLeft.row(), 1)).toString().toLatin1()); emit ToolsChanged(); break; case QmitkNDIToolDelegate::SROMCol: //SROM File Name { QString romfile = model->data(model->index(topLeft.row(), QmitkNDIToolDelegate::SROMCol)).toString(); if (QFileInfo(romfile).exists()) tool->LoadSROMFile(romfile.toLatin1()); m_Tracker->UpdateTool(tool); break; } //TODO: Add Node Status and Type here as well default: break; } } const QString QmitkNDIConfigurationWidget::GetToolType( unsigned int index ) const { if (m_Controls == NULL) return QString(""); QAbstractItemModel* model = m_Controls->m_ToolTable->model(); QModelIndex modelIndex = model->index(index, QmitkNDIToolDelegate::TypeCol); if (modelIndex.isValid() == false) return QString(""); return model->data(modelIndex).toString(); } const QString QmitkNDIConfigurationWidget::GetToolName( unsigned int index ) const { if (m_Controls == NULL) return QString(""); QAbstractItemModel* model = m_Controls->m_ToolTable->model(); QModelIndex modelIndex = model->index(index, QmitkNDIToolDelegate::NameCol); if (modelIndex.isValid() == false) return QString(""); return model->data(modelIndex).toString(); } QMap QmitkNDIConfigurationWidget::GetToolAndTypes() const { QMap map; if (m_Controls == NULL) return map; QAbstractItemModel* model = m_Controls->m_ToolTable->model(); for (int i = 0; i < model->rowCount(); ++i) { QModelIndex indexIndex = model->index(i, QmitkNDIToolDelegate::IndexCol); QModelIndex typeIndex = model->index(i, QmitkNDIToolDelegate::TypeCol); if ((indexIndex.isValid() == false) || (typeIndex.isValid() == false)) continue; map.insert(model->data(typeIndex).toString(), model->data(indexIndex).toUInt()); } return map; } QList QmitkNDIConfigurationWidget::GetToolsByToolType( QString toolType ) const { QList list; if (m_Controls == NULL) return list; QAbstractItemModel* model = m_Controls->m_ToolTable->model(); for (int i = 0; i < model->rowCount(); ++i) { QModelIndex indexIndex = model->index(i, QmitkNDIToolDelegate::IndexCol); QModelIndex typeIndex = model->index(i, QmitkNDIToolDelegate::TypeCol); if ((indexIndex.isValid() == false) || (typeIndex.isValid() == false)) continue; if (model->data(typeIndex).toString() == toolType) list.append(model->data(indexIndex).toUInt()); } return list; } mitk::DataNode* QmitkNDIConfigurationWidget::GetNode( unsigned int index ) const { if (m_Controls == NULL) return NULL; QAbstractItemModel* model = m_Controls->m_ToolTable->model(); QVariant data = model->data(model->index(index, QmitkNDIToolDelegate::NodeCol), QmitkNDIToolDelegate::OrganNodeRole); return data.value(); } void QmitkNDIConfigurationWidget::HidePolarisOptionsGroupbox( bool on ) { m_Controls->m_gbPolarisOptions->setHidden(on); } void QmitkNDIConfigurationWidget::HideAuroraOptionsGroupbox( bool on ) { m_Controls->m_gbAuroraOptions->setHidden(on); } void QmitkNDIConfigurationWidget::ShowToolRepresentationColumn() { int cols = m_Controls->m_ToolTable->columnCount(); //checking if representation column is inserted at right index if(cols != QmitkNDIToolDelegate::RepCol) { //throw std::exception("Representation Column is not inserted at it's designated index!"); return; } m_Controls->m_ToolTable->insertColumn(cols); // insert new column at end of table m_Controls->m_ToolTable->setHorizontalHeaderItem(QmitkNDIToolDelegate::RepCol, new QTableWidgetItem(QString("Representation"))); // inser column header for new colum //m_Controls->m_ToolTable->setEditTriggers(QAbstractItemView::EditTrigger::NoEditTriggers); int rows = m_Controls->m_ToolTable->rowCount(); // make all representation colum items not editable for(int i=0; i < rows; ++i) { m_Controls->m_ToolTable->setItem(i, QmitkNDIToolDelegate::RepCol, new QTableWidgetItem("")); // Representation m_Controls->m_ToolTable->item(i,QmitkNDIToolDelegate::RepCol)->setFlags(Qt::NoItemFlags); } //connect(m_Controls->m_ToolTable, SIGNAL( clicked ( const QModelIndex & )), this, SLOT ( OnTableItemClicked( const QModelIndex & ))); } void QmitkNDIConfigurationWidget::OnDisoverDevicesBtnInfo() { QMessageBox *infoBox = new QMessageBox(this); infoBox->setText("Click \"Scan Ports\" to get a list of all connected NDI tracking devices. This will clear the selection menu below and add the ports for discovered NDI tracking devices. Use this function, if a port is not listed."); infoBox->exec(); delete infoBox; } void QmitkNDIConfigurationWidget::OnTableCellChanged(int row, int column) { if(m_Tracker.IsNull()) return; QString toolName; switch (column) { case QmitkNDIToolDelegate::NameCol: toolName = m_Controls->m_ToolTable->item(row,column)->text(); m_Controls->m_ToolSelectionComboBox->setItemText(row, toolName); emit SignalToolNameChanged(row, toolName); break; default: break; } } void QmitkNDIConfigurationWidget::OnSaveTool() { if(m_Tracker.IsNull() || m_Tracker->GetToolCount() <= 0) return; int currId = m_Controls->m_ToolSelectionComboBox->currentIndex(); QString filename = QFileDialog::getSaveFileName(NULL, "Save NDI-Tool", QString(QDir::currentPath()+QString(m_Tracker->GetTool(currId)->GetToolName())),"NDI Tracking Tool file(*.ntf)"); mitk::TrackingTool* selectedTool = m_Tracker->GetTool(currId); if(filename.isEmpty()) return; mitk::NavigationTool::Pointer navTool = mitk::NavigationTool::New(); mitk::NavigationToolWriter::Pointer toolWriter = mitk::NavigationToolWriter::New(); try { toolWriter->DoWrite(filename.toStdString(), this->GenerateNavigationTool(selectedTool)); } catch( ... ) { QMessageBox::warning(NULL, "Saving Tool Error", QString("An error occured! Could not save tool!\n\n")); MBI_ERROR<<"Could not save tool surface!"; MBI_ERROR<< toolWriter->GetErrorMessage(); QFile maybeCorruptFile(filename); if(maybeCorruptFile.exists()) maybeCorruptFile.remove(); } emit SignalSavedTool(currId, filename); } void QmitkNDIConfigurationWidget::OnLoadTool() { if(m_Tracker.IsNull() || m_Tracker->GetToolCount() <= 0) return; QString filename = QFileDialog::getOpenFileName(NULL, "Load NDI-Tools", QDir::currentPath(),"NDI Tracking Tool file(*.ntf)"); int currId = m_Controls->m_ToolSelectionComboBox->currentIndex(); if(filename.isEmpty()) return; mitk::DataNode::Pointer toolNode; mitk::NavigationToolReader::Pointer toolReader = mitk::NavigationToolReader::New(); mitk::NavigationTool::Pointer navTool; try { navTool = toolReader->DoRead(filename.toStdString()); } catch( ... ) { QMessageBox::warning(NULL, "Loading Tool Error", QString("An error occured! Could not load tool!\n\n")); MBI_ERROR<<"Could not load tool surface!"; MBI_ERROR<< toolReader->GetErrorMessage(); } int currSelectedToolID = m_Controls->m_ToolSelectionComboBox->currentIndex(); // name m_Controls->m_ToolTable->item(currSelectedToolID,QmitkNDIToolDelegate::NameCol)->setText(navTool->GetToolName().c_str()); dynamic_cast(m_Tracker->GetTool(currSelectedToolID))->SetToolName(navTool->GetToolName().c_str()); // also setting name to tool directly //calibration file (.srom) filename m_Controls->m_ToolTable->item(currSelectedToolID,QmitkNDIToolDelegate::SROMCol)->setText(navTool->GetCalibrationFile().c_str()); //type if(navTool->GetType() == mitk::NavigationTool::Instrument) m_Controls->m_ToolTable->item(currSelectedToolID,QmitkNDIToolDelegate::TypeCol)->setText("Instrument"); else if(navTool->GetType() == mitk::NavigationTool::Fiducial) m_Controls->m_ToolTable->item(currSelectedToolID,QmitkNDIToolDelegate::TypeCol)->setText("Fiducial"); else if(navTool->GetType() == mitk::NavigationTool::Skinmarker) m_Controls->m_ToolTable->item(currSelectedToolID,QmitkNDIToolDelegate::TypeCol)->setText("Skinmarker"); else m_Controls->m_ToolTable->item(currSelectedToolID,QmitkNDIToolDelegate::TypeCol)->setText("Unknown"); //representation m_Controls->m_ToolTable->item(currSelectedToolID,QmitkNDIToolDelegate::SROMCol)->setText(m_RepresentatonCellDefaultText); emit SignalLoadTool(currId, navTool->GetDataNode()); } mitk::NavigationTool::Pointer QmitkNDIConfigurationWidget::GenerateNavigationTool(mitk::TrackingTool* tool) { mitk::NavigationTool::Pointer navTool = mitk::NavigationTool::New(); mitk::NDIPassiveTool::Pointer passiveTool = dynamic_cast(tool); if(passiveTool.IsNull()) throw std::runtime_error("Could not cast TrackingTool to PassiveTool"); int currSelectedToolID = m_Controls->m_ToolSelectionComboBox->currentIndex(); QString sromFileName = m_Controls->m_ToolTable->item(currSelectedToolID, QmitkNDIToolDelegate::SROMCol)->text(); QString surfaceFileName = m_Controls->m_ToolTable->item(currSelectedToolID, QmitkNDIToolDelegate::RepCol)->text(); //calibration file (.srom) filename QFile sromFile(sromFileName); if(sromFile.exists()) navTool->SetCalibrationFile(sromFileName.toStdString()); //serial number navTool->SetSerialNumber(passiveTool->GetSerialNumber()); // name and surface as dataNode mitk::DataNode::Pointer node = mitk::DataNode::New(); mitk::Surface::Pointer toolSurface; try{ toolSurface = this->LoadSurfaceFromSTLFile(surfaceFileName); } catch( ... ) { QMessageBox::warning(NULL, "Loading Surface Error", QString("An error occured! Could not load surface from .stl file!\n\n")); MBI_ERROR<<"Could not load .stl tool surface!"; } if(toolSurface.IsNotNull()) { node->SetData(toolSurface); node->SetName(tool->GetToolName()); } navTool->SetDataNode(node); // type mitk::NavigationTool::NavigationToolType type; QString currentToolType = m_Controls->m_ToolTable->item(currSelectedToolID,QmitkNDIToolDelegate::TypeCol)->text(); if(currentToolType.compare("Instrument") == 0) type = mitk::NavigationTool::Instrument; else if(currentToolType.compare("Fiducial") == 0) type = mitk::NavigationTool::Fiducial; else if(currentToolType.compare("Skinmarker") == 0) type = mitk::NavigationTool::Skinmarker; else type = mitk::NavigationTool::Unknown; navTool->SetType(type); return navTool; } mitk::Surface::Pointer QmitkNDIConfigurationWidget::LoadSurfaceFromSTLFile(QString surfaceFilename) { mitk::Surface::Pointer toolSurface; QFile surfaceFile(surfaceFilename); if(surfaceFile.exists()) { mitk::STLFileReader::Pointer stlReader = mitk::STLFileReader::New(); try{ stlReader->SetFileName(surfaceFilename.toStdString().c_str()); stlReader->Update();//load surface toolSurface = stlReader->GetOutput(); } catch(std::exception& e ) { MBI_ERROR<<"Could not load surface for tool!"; MBI_ERROR<< e.what(); throw e; } } return toolSurface; -} \ No newline at end of file +} + +void QmitkNDIConfigurationWidget::EnableAddToolsButton(bool enable) { + m_Controls->m_AddToolBtn->setEnabled(enable); +} diff --git a/Modules/IGTUI/Qmitk/QmitkNDIConfigurationWidget.h b/Modules/IGTUI/Qmitk/QmitkNDIConfigurationWidget.h index 5b235be80b..6b660105d2 100644 --- a/Modules/IGTUI/Qmitk/QmitkNDIConfigurationWidget.h +++ b/Modules/IGTUI/Qmitk/QmitkNDIConfigurationWidget.h @@ -1,136 +1,137 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-03-21 19:27:37 +0100 (Sa, 21 Mrz 2009) $ Version: $Revision: 16719 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _QmitkNDIConfigurationWidget_H_INCLUDED #define _QmitkNDIConfigurationWidget_H_INCLUDED #include "ui_QmitkNDIConfigurationWidget.h" #include "mitkNDITrackingDevice.h" #include "mitkTrackingDeviceSource.h" #include "QStringList" #include "MitkIGTUIExports.h" #include "mitkNodePredicateBase.h" #include "mitkNavigationTool.h" class QmitkNDIToolDelegate; namespace mitk { class DataStorage; }; /*! \brief Heidelberg Minimally Invasive Navigation Device Functionality for visualizing a tracking instrument in relation to a tracked patient. \sa QmitkFunctionality \sa IGT \ingroup Functionalities */ class MitkIGTUI_EXPORT QmitkNDIConfigurationWidget : public QWidget { Q_OBJECT // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) public: QmitkNDIConfigurationWidget(QWidget* parent); virtual ~QmitkNDIConfigurationWidget(); std::string GetDeviceName() const; mitk::NDITrackingDevice* GetTracker() const; mitk::DataStorage* GetDataStorage() const; mitk::NodePredicateBase* GetPredicate() const; const QStringList& GetToolTypes() const; void SetToolTypes(const QStringList& types); ///< set types list for type editor combobox void SetDataStorage(mitk::DataStorage* ds); ///< set datastorage for organ node editor void SetPredicate(mitk::NodePredicateBase::Pointer p); ///< set predicate for organ node editor void SetTagPropertyName(const std::string& name); ///< set name of the property that is used to tag selected nodes void SetTagProperty(mitk::BaseProperty::Pointer prop); ///< set the property that is used to tag selected nodes const QString GetToolType(unsigned int index) const; const QString GetToolName(unsigned int index) const; QMap GetToolAndTypes() const; QList GetToolsByToolType(QString toolType) const; mitk::DataNode* GetNode(unsigned int index) const; signals: void ToolsAdded(QStringList tools); void ToolsChanged(); void Connected(); void Disconnected(); void RepresentationChanged( int row , mitk::Surface::Pointer surface ); // returns the row number of the clicked tableitem for changing tool representation void SignalToolNameChanged(int id, QString name); void SignalSavedTool(int id, QString surfaceFilename); void SignalLoadTool(int id, mitk::DataNode::Pointer dn); public slots: void SetDeviceName(const char* dev); ///< set the device name (e.g. "COM1", "/dev/ttyS0") that will be used to connect to the tracking device void ShowToolRepresentationColumn(); ///< show or hide the tooltable column "Tool Representation". This SLOT should be called after SIGNAL "Connected" is emitted - + void EnableAddToolsButton(bool enable); ///< enables or disables the Add Tools button + protected slots: void OnConnect(); void OnDisconnect(); void OnDiscoverTools(); void OnDiscoverDevices(); void OnAddPassiveTool(); void UpdateTrackerFromToolTable(const QModelIndex & topLeft, const QModelIndex & /*bottomRight*/); void OnTableItemClicked(const QModelIndex & topLeft); ///< for clicking on tooltable items void OnDisoverDevicesBtnInfo(); void OnTableCellChanged(int row, int column); void OnSaveTool(); void OnLoadTool(); protected: typedef QMap PortDeviceMap; // key is port name (e.g. "COM1", "/dev/ttyS0"), value will be filled with the type of tracking device at this port /**Documentation * \brief scans the ports provided as key in the portsAndDevices and fills the respective value of portsAndDevices with the tracking device type at that port * * * \param[in] portsAndDevices keys are used to query serial ports * \param[out] portsAndDevices values of the existing keys will be filled with the tracking device type */ void ScanPortsForNDITrackingDevices(PortDeviceMap& portsAndDevices); mitk::TrackingDeviceType ScanPort(QString port); mitk::NavigationTool::Pointer GenerateNavigationTool(mitk::TrackingTool* tool); QStringList GetToolNamesList(); ///< returns a string list with the names of all tools of the current tracking device void CreateTracker(); ///< creates new NDITrackingDevice object void SetupTracker(); ///< sets the parameters from the gui to the tracking device object QString GetStatusText(); ///< construct a status text depending on the current state of the tracking device object void UpdateWidgets(); void UpdateToolTable(); ///< read all tools from the tracking device object and display them in the gui virtual void CreateQtPartControl(QWidget *parent); virtual void CreateConnections(); ///< \brief Creation of the connections of main and control widget void HidePolarisOptionsGroupbox( bool on ); ///< show or hide polaris options in the UI void HideAuroraOptionsGroupbox( bool on ); ///< show or hide aurora options in the UI Ui::QmitkNDIConfigurationWidget* m_Controls; ///< gui widgets mitk::NDITrackingDevice::Pointer m_Tracker; ///< tracking device object mitk::TrackingDeviceSource::Pointer m_Source; QmitkNDIToolDelegate* m_Delegate; QString m_SROMCellDefaultText; QString m_RepresentatonCellDefaultText; mitk::Surface::Pointer LoadSurfaceFromSTLFile(QString surfaceFilename); }; #endif // _QmitkNDIConfigurationWidget_H_INCLUDED