void CalibrationWindow::Act_Load_nii() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), "E:/", tr("Image Files (*.nii)")); if (fileName.isEmpty()) { return; } auto reader = vtkSmartPointer<vtkNIFTIImageReader>::New(); reader->SetFileName(fileName.toStdString().c_str()); reader->Update(); //extract 3d model auto marchingCubes = vtkSmartPointer<vtkMarchingCubes>::New(); marchingCubes->SetInputData(reader->GetOutput()); marchingCubes->SetValue(0, 500); marchingCubes->Update(); auto mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputData(marchingCubes->GetOutput()); m_Actor2 = vtkSmartPointer<vtkActor>::New(); m_Actor2->SetMapper(mapper); m_Renderer->AddActor(m_Actor2); m_Renderer->ResetCamera(); m_View->Render(); }
void main(){ typedef itk::Image<signed short, 2> imagetype; typedef itk::ImageFileReader<imagetype> imagereadertype; typedef itk::ImageToVTKImageFilter<imagetype> connerctortypr; imagereadertype::Pointer reader = imagereadertype::New(); reader->SetFileName("e:/IM-0001-0001.dcm"); auto iotype = itk::GDCMImageIO::New(); reader->SetImageIO(iotype); try{ reader->Update(); } catch (itk::ExceptionObject e){ std::cerr << "exception in file reader " << std::endl; std::cerr << e.GetDescription() << std::endl; std::cerr << e.GetLocation() << std::endl; } connerctortypr::Pointer connector = connerctortypr::New(); connector->SetInput(reader->GetOutput()); connector->Update(); auto flip = vtkImageFlip::New(); flip->SetInputData(connector->GetOutput()); flip->SetFilteredAxis(1); flip->Update(); auto actor = vtkImageActor::New(); //actor->GetMapper()->SetInputData(flip->GetOutput()); actor->SetInputData(flip->GetOutput()); actor->InterpolateOff(); actor->Update(); auto render = vtkRenderer::New(); render->AddActor(actor); auto window = vtkRenderWindow::New(); window->SetSize(800, 600); window->AddRenderer(render); auto interactor = vtkRenderWindowInteractor::New(); interactor->SetRenderWindow(window); interactor->Initialize(); interactor->Start(); }
void MainWindow::on_ResliceActionMarker(double x, double y, double z) { int pt_ID = 0; pt_ID = m_Image->FindPoint(x, y, z); std::cout << "Point ID is: " << pt_ID << std::endl; int extent[6]; m_Image->GetExtent(extent); int x_e = extent[1] - extent[0] + 1; int y_e = extent[3] - extent[2] + 1; int z_e = extent[5] - extent[4] + 1; m_SliceZ = floor(pt_ID / (x_e*y_e)); m_SliceY = floor(pt_ID % (x_e*y_e) / x_e); m_SliceX = pt_ID%x_e; m_3d_View->PopObject(); auto ball = vtkSmartPointer<vtkSphereSource>::New(); ball->SetRadius(5.0); ball->SetPhiResolution(50); ball->SetThetaResolution(50); ball->Update(); auto mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputData(ball->GetOutput()); auto ball_actor = vtkSmartPointer<vtkActor>::New(); ball_actor->SetMapper(mapper); ball_actor->GetProperty()->SetColor(1.0, 0.0, 0.0); ball_actor->SetPosition(x, y, z); m_3d_View->AddObject(ball_actor); m_3d_View->RefreshView(); }
void CalibrationWindow::Act_LoadSTL() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), "E:/", tr("Image Files (*.stl)")); if (fileName.isEmpty()) { return; } auto reader = vtkSmartPointer<vtkSTLReader>::New(); reader->SetFileName(fileName.toStdString().c_str()); reader->Update(); auto image = vtkSmartPointer<vtkPolyData>::New(); image = reader->GetOutput(); auto mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputData(image); m_Actor = vtkSmartPointer<vtkActor>::New(); m_Actor->SetMapper(mapper); //vtkSmartPointer<vtkAxesActor> axes = // vtkSmartPointer<vtkAxesActor>::New(); //axes->SetTotalLength(200.0, 200.0, 200.0); // //m_Actor = axes; m_Renderer->AddActor(m_Actor); m_Renderer->ResetCamera(); m_View->Render(); }
vtkSmartPointer<vtkChartXY> chart_from_histogram( const THisto& input_histo, vtkIdType chart_type = vtkChart::LINE) { auto chart = vtkSmartPointer<vtkChartXY>::New(); vtkNew<vtkTable> table; table->SetNumberOfRows(input_histo.bins); vtkNew<vtkFloatArray> xArray; xArray->SetName("Bins"); xArray->SetNumberOfValues(input_histo.bins); table->AddColumn(xArray.GetPointer()); vtkNew<vtkFloatArray> yArray; yArray->SetName("Counts"); yArray->SetNumberOfValues(input_histo.bins); table->AddColumn(yArray.GetPointer()); auto centers = input_histo.ComputeBinCenters(); for(size_t j = 0; j != input_histo.bins; j++) { xArray->SetValue(j, centers[j]); yArray->SetValue(j, input_histo.counts[j]); } // auto const &xAxis = chart->GetAxis(vtkAxis::BOTTOM) ; // xAxis->SetRange(input_histo.range.first, input_histo.range.second); // xAxis->SetTitle(input_histo.name); // xAxis->SetBehavior(vtkAxis::FIXED); // chart->GetAxis(vtkAxis::LEFT)->SetBehavior(vtkAxis::FIXED); // chart->GetAxis(vtkAxis::BOTTOM)->SetBehavior(vtkAxis::FIXED); chart->GetAxis(vtkAxis::LEFT)->SetTitle("#"); chart->GetAxis(vtkAxis::BOTTOM)->SetTitle("bins"); chart->SetTitle(input_histo.name); auto points = chart->AddPlot(chart_type); points->SetInputData(table, 0, 1); return chart; }
bool Exporter::exportVTKXMLImageData(DataObject & image, const QString & fileName) { auto writer = vtkSmartPointer<vtkXMLImageDataWriter>::New(); writer->SetInputData(image.dataSet()); return writeVTKXML(writer, fileName); }
/* Begin selecting marker */ void MainWindow::on_Sel_Markers() { QMessageBox msgBox; msgBox.setText("Select Marker."); //msgBox.setInformativeText("Press \"a\" to accept the marker.\nPress \"b\" to abort. \nPress \"q\" to finish."); msgBox.setInformativeText("Put the Tool in the corresponding place and press \"Capture\" "); msgBox.setStandardButtons(QMessageBox::Ok); int ret = msgBox.exec(); auto ball = vtkSmartPointer<vtkSphereSource>::New(); ball->SetRadius(5.0); ball->SetPhiResolution(50); ball->SetThetaResolution(50); ball->Update(); auto mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputData(ball->GetOutput()); auto ball_actor = vtkSmartPointer<vtkActor>::New(); ball_actor->SetMapper(mapper); ball_actor->GetProperty()->SetColor(1.0, 0.0, 0.0); m_3d_View->AddObject(ball_actor); m_3d_View->RefreshView(); disconnect(m_3d_View, SIGNAL(on_timer_signal_coor(double, double, double)), this, SLOT(on_ResliceAction(double, double, double))); connect(m_3d_View, SIGNAL(on_timer_signal_coor(double, double, double)), this, SLOT(on_ResliceActionMarker(double, double, double))); // enable mouse pick first m_3d_View->EnablePick(); //press a to accept }
LRESULT COXMaskedEdit::OnSetText(WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(wParam); UNREFERENCED_PARAMETER(lParam); if(m_listData.GetCount()==0 || GetStyle()&ES_READONLY) { return CEdit::Default(); } CString csNewString=(LPCTSTR)lParam; if(m_nSetTextSemaphor>0) { LRESULT result=CEdit::Default(); NotifyParent(EN_UPDATE); if(m_bNotifyParent) NotifyParent(EN_CHANGE); return result; } else { ASSERT(m_nSetTextSemaphor==0); m_bNotifyParent=FALSE; csNewString=GetInputData(csNewString); SetInputData(csNewString,0,TRUE); m_bNotifyParent=TRUE; return TRUE; } }
int COXMaskedEdit::DeleteRange(int nSelectionStart, int nSelectionEnd) { // In order to delete properly, we must count the number of // input characters that are selected and only delete that many. // This is because the selection can include literals. int nCharIndex =0; int nDeleteCount=0; CString csInputData; CMaskData* pobjData=NULL; for(POSITION pos=m_listData.GetHeadPosition(); pos; nCharIndex++) { pobjData=m_listData.GetNext(pos); // Ignore everything that is not data. // This is just like we do in GetInputData except that we // will ignore the input data within the selection range. if(pobjData->IsInputData()) { if((nCharIndex < nSelectionStart) || (nCharIndex >= nSelectionEnd)) { // The SetInputData() function will take care of validating // the shifted characters. csInputData += pobjData->m_chValue; } else nDeleteCount++; } } // Now apply the filtered data stream. SetInputData(csInputData); // return the deleted count so that an error can be generated // if none were deleted. return nDeleteCount; }
void wxMaskController::SetValue(wxString& value) { if(m_listData.GetCount() == 0) SetTextValue(value); else SetInputData(GetInputData(value), 0, true); }
int wxMaskController::InsertAt(int nSelectionStart, wxChar chNewChar) { // Although we could have some complex, yet efficient, routine // that would error if inserting pushed an existing character // into an invalid region. Instead, just save the current // state and restore it on error. wxString csPreviousInput=GetInputData(); int nCharIndex = 0; int nInsertionPoint = -1; wxString csInputData; wxFieldMaskData* pobjData = NULL; for(unsigned long pos = 0;pos < m_listData.GetCount(); pos++,nCharIndex++) { pobjData = (wxFieldMaskData *) (m_listData.Item(pos))->GetData(); // Ignore everything that is not data. // This is just like we do in GetInputData except that we // will ignore the input data within the selection range. if(pobjData->IsInputData()) { // Wait until a valid insertion point and // only make sure to insert once. if((nInsertionPoint < 0) && (nCharIndex >= nSelectionStart)) { csInputData += chNewChar; nInsertionPoint=nCharIndex; } csInputData += pobjData->m_chValue; } } // Now apply the filtered data stream and check if it was successful. if(!SetInputData(csInputData)) { // If not successful, then restore the previous input and return -1. SetInputData(csPreviousInput); return -1; } return nInsertionPoint; }
int COXMaskedEdit::InsertAt(int nSelectionStart, TCHAR chNewChar) { // Although we could have some complex, yet efficient, routine // that would error if inserting pushed an existing character // into an invalid region. Instead, just save the current // state and restore it on error. CString csPreviousInput=GetInputData(); int nCharIndex=0; int nInsertionPoint=-1; CString csInputData; CMaskData* pobjData=NULL; for(POSITION pos=m_listData.GetHeadPosition(); pos; nCharIndex++) { pobjData=m_listData.GetNext(pos); // Ignore everything that is not data. // This is just like we do in GetInputData except that we // will ignore the input data within the selection range. if(pobjData->IsInputData()) { // Wait until a valid insertion point and // only make sure to insert once. if((nInsertionPoint < 0) && (nCharIndex >= nSelectionStart)) { csInputData += chNewChar; nInsertionPoint=nCharIndex; } csInputData += pobjData->m_chValue; } } // Now apply the filtered data stream and check if it was successful. if(!SetInputData(csInputData)) { // If not successful, then restore the previous input and return -1. SetInputData(csPreviousInput); return -1; } return nInsertionPoint; }
void MainWindow::on_Load_Image() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), "E:/", tr("Image Files (*.nii)")); if (fileName.isEmpty()) { return; } else { m_ImageFileName = fileName.toStdString(); auto reader = vtkSmartPointer<vtkNIFTIImageReader>::New(); reader->SetFileName(m_ImageFileName.c_str()); reader->Update(); m_Image = reader->GetOutput(); //modify slider range int extent[6]; m_SliceX = (extent[5] + extent[4]) / 2; m_SliceY = (extent[0] + extent[1]) / 2; m_SliceZ = (extent[2] + extent[3]) / 2; m_Image->GetExtent(extent); ui->axial_slider->setRange(extent[4], extent[5]); ui->axial_slider->setValue(m_SliceX); ui->sagittal_slider->setRange(extent[0], extent[1]); ui->sagittal_slider->setValue(m_SliceY); ui->coronal_slider->setRange(extent[2], extent[3]); ui->coronal_slider->setValue(m_SliceZ); m_Sagittal_View->Set_View_Img(m_Image); m_Axial_View->Set_View_Img(m_Image); m_Coronal_View->Set_View_Img(m_Image); m_Sagittal_View->RenderView(); m_Axial_View->RenderView(); m_Coronal_View->RenderView(); m_3d_View->SetImage(m_Image); //extract 3d model auto marchingCubes = vtkSmartPointer<vtkMarchingCubes>::New(); marchingCubes->SetInputData(m_Image); marchingCubes->SetValue(0, m_StripValue); marchingCubes->Update(); m_3d_View->AddPolySource(marchingCubes->GetOutput()); m_3d_View->SetColor(0, 0.5, 0.6, 0.7); m_3d_View->ResetView(); } }
string FlowAnalysis::vtkWriteGrid(const string& out, vtkSmartPointer<vtkUniformGrid>& grid){ auto compressor=vtkSmartPointer<vtkZLibDataCompressor>::New(); auto writer=vtkSmartPointer<vtkXMLImageDataWriter>::New(); string fn=scene->expandTags(out)+".vti"; writer->SetFileName(fn.c_str()); #if VTK_MAJOR_VERSION==5 writer->SetInput(grid); #else writer->SetInputData(grid); #endif // writer->SetDataModeToAscii(); writer->SetCompressor(compressor); writer->Write(); return fn; }
TEST_F(DEMImageNormals_test, NormalsAreNormalized) { auto demNormalFilter = vtkSmartPointer<DEMImageNormals>::New(); demNormalFilter->SetCoordinatesUnitScale(1.0); demNormalFilter->SetElevationUnitScale(1.0); demNormalFilter->SetInputData(dem); ASSERT_TRUE(demNormalFilter->GetExecutive()->Update()); auto normals = demNormalFilter->GetOutput()->GetPointData()->GetNormals(); ASSERT_TRUE(normals); ASSERT_EQ(dem->GetNumberOfPoints(), normals->GetNumberOfTuples()); for (vtkIdType i = 0; i < normals->GetNumberOfTuples(); ++i) { vtkVector3d normal; normals->GetTuple(i, normal.GetData()); ASSERT_FLOAT_EQ(1.f, static_cast<float>(normal.Norm())); } }
void CalibrationWindow::Act_CreateDefault() { auto arrow = vtkSmartPointer<vtkCylinderSource>::New(); arrow->SetHeight(300); arrow->SetRadius(50); //arrow->SetCenter(0,100,0); arrow->Update(); auto image = vtkSmartPointer<vtkPolyData>::New(); image = arrow->GetOutput(); auto mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputData(image); auto axes = vtkSmartPointer<vtkAxesActor>::New(); axes->SetTotalLength(300, 300, 300); //m_Actor2 = axes; m_Renderer->AddActor(m_Actor2); m_Renderer->ResetCamera(); m_View->Render(); }
void StackedImageDataLIC3D::SimpleExecute(vtkImageData * input, vtkImageData * output) { vtkDataArray * vectors = input->GetPointData()->GetVectors(); if (!vectors) { vtkGenericWarningMacro("StackeImageDataLIC3D::SimpleExecute: missing input vectors"); return; } initialize(); auto appendTo3D = vtkSmartPointer<vtkImageAppend>::New(); appendTo3D->SetAppendAxis(2); int inputExtent[6]; input->GetExtent(inputExtent); for (int position = inputExtent[4]; position < inputExtent[5]; ++position) { int sliceExtent[6]; input->GetExtent(sliceExtent); sliceExtent[4] = sliceExtent[5] = position; auto slice = vtkSmartPointer<vtkExtractVOI>::New(); slice->SetVOI(sliceExtent); slice->SetInputData(input); auto lic2D = vtkSmartPointer<vtkImageDataLIC2D>::New(); lic2D->SetInputConnection(0, slice->GetOutputPort()); lic2D->SetInputConnection(1, m_noiseImage->GetOutputPort()); lic2D->SetSteps(50); lic2D->GlobalWarningDisplayOff(); lic2D->SetContext(m_glContext); appendTo3D->AddInputConnection(lic2D->GetOutputPort()); } appendTo3D->Update(); output->DeepCopy(appendTo3D->GetOutput()); }
int wxMaskController::DeleteRange(int nSelectionStart, int nSelectionEnd) { // In order to delete properly, we must count the number of // input characters that are selected and only delete that many. // This is because the selection can include literals. int nCharIndex =0; int nDeleteCount=0; wxString csInputData; wxFieldMaskData* pobjData = NULL; m_bNeedValidation = TRUE; m_bValidation = FALSE; for(unsigned long pos = 0;pos < m_listData.GetCount(); pos++,nCharIndex++) { pobjData = (wxFieldMaskData *) (m_listData.Item(pos))->GetData(); // Ignore everything that is not data. // This is just like we do in GetInputData except that we // will ignore the input data within the selection range. if(pobjData->IsInputData()) { if((nCharIndex < nSelectionStart) || (nCharIndex >= nSelectionEnd)) { // The SetInputData() function will take care of validating // the shifted characters. csInputData += pobjData->m_chValue; } else nDeleteCount++; } } // Now apply the filtered data stream. SetInputData(csInputData); // return the deleted count so that an error can be generated // if none were deleted. return nDeleteCount; }
LRESULT COXMaskedEdit::OnPaste(WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(wParam); UNREFERENCED_PARAMETER(lParam); if(m_listData.GetCount()==0 || GetStyle()&ES_READONLY) { return CEdit::Default(); } int nSelectionStart=0; int nSelectionEnd =0; GetSel(nSelectionStart, nSelectionEnd); CEdit::Default(); // This is a real dump paste routine that expects SetInputData do // do the filtering. There is probably no easy solution to this // task because anything can be pasted. We could try and match // the literals, but maybe we will get to that later. CString csNewString; GetWindowText(csNewString); // It is very important that we do not allow the prompt character // in this scenario. This is because we expect the pasted text // to contain lots of literals and spaces. SetInputData(csNewString, 0, FALSE); Update(-1); // Setting the insertion point after a paste is tricky because the // expected location is after the last valid pasted character. // Try and determine this location by setting the insertion point // to the first empty location after the specified starting point. int nNewInsertionPoint=GetEmptyInputLocation(nSelectionStart); SetSel(nNewInsertionPoint, nNewInsertionPoint); return 0; }
vtkSmartPointer<vtkPolyData> VoxelCarving::createVisualHull( const double isolevel) const { // create vtk visualization pipeline from voxel grid auto spoints = vtkSmartPointer<vtkStructuredPoints>::New(); auto vdim = static_cast<int>(voxel_dim_); spoints->SetDimensions(vdim, vdim, vdim); spoints->SetSpacing(params_.voxel_width, params_.voxel_height, params_.voxel_depth); spoints->SetOrigin(params_.start_x, params_.start_y, params_.start_z); auto farray = vtkSmartPointer<vtkFloatArray>::New(); auto vsize = static_cast<vtkIdType>(voxel_size_); farray->SetNumberOfValues(vsize); farray->SetArray(vox_array_.get(), vsize, 1); spoints->GetPointData()->SetScalars(farray); // create iso surface with marching cubes auto mc_source = vtkSmartPointer<vtkMarchingCubes>::New(); #if VTK_MAJOR_VERSION < 6 mc_source->SetInput(spoints); #else mc_source->SetInputData(spoints); #endif mc_source->SetNumberOfContours(1); mc_source->SetValue(0, isolevel); // calculate surface normals auto surface_normals = vtkSmartPointer<vtkPolyDataNormals>::New(); surface_normals->SetInputConnection(mc_source->GetOutputPort()); surface_normals->SetFeatureAngle(60.0); surface_normals->ComputePointNormalsOn(); surface_normals->Update(); return surface_normals->GetOutput(); }
std::string dump(Mesh* mesh, int step, std::string fileName) const { auto _mesh = dynamic_cast<MeshType*>(mesh); assert_true(_mesh); LOG_DEBUG("Writing snapshot for mesh \"" << _mesh->getId() << "\" at step " << step << " to file " << fileName); auto grid = vtkSmartPointer<GridType>::New(); auto points = vtkSmartPointer<vtkPoints>::New(); auto contact = vtkSmartPointer<vtkIntArray>::New(); contact->SetName("contact"); auto border = vtkSmartPointer<vtkIntArray>::New(); border->SetName("border"); auto used = vtkSmartPointer<vtkIntArray>::New(); used->SetName("used"); auto norm = vtkSmartPointer<vtkDoubleArray>::New(); norm->SetName("norm"); norm->SetNumberOfComponents(3); auto vel = vtkSmartPointer<vtkDoubleArray>::New(); vel->SetName("velocity"); vel->SetNumberOfComponents(3); auto crack = vtkSmartPointer<vtkDoubleArray>::New(); crack->SetName("crack"); crack->SetNumberOfComponents(3); auto sxx = vtkSmartPointer<vtkDoubleArray>::New(); sxx->SetName("sxx"); auto sxy = vtkSmartPointer<vtkDoubleArray>::New(); sxy->SetName("sxy"); auto sxz = vtkSmartPointer<vtkDoubleArray>::New(); sxz->SetName("sxz"); auto syy = vtkSmartPointer<vtkDoubleArray>::New(); syy->SetName("syy"); auto syz = vtkSmartPointer<vtkDoubleArray>::New(); syz->SetName("syz"); auto szz = vtkSmartPointer<vtkDoubleArray>::New(); szz->SetName("szz"); auto compression = vtkSmartPointer<vtkDoubleArray>::New(); compression->SetName("compression"); auto tension = vtkSmartPointer<vtkDoubleArray>::New(); tension->SetName("tension"); auto shear = vtkSmartPointer<vtkDoubleArray>::New(); shear->SetName("shear"); auto deviator = vtkSmartPointer<vtkDoubleArray>::New(); deviator->SetName("deviator"); auto matId = vtkSmartPointer<vtkIntArray>::New(); matId->SetName("materialID"); auto rho = vtkSmartPointer<vtkDoubleArray>::New(); rho->SetName("rho"); auto mpiState = vtkSmartPointer<vtkIntArray>::New(); mpiState->SetName("mpiState"); auto nodePublicFlags = vtkSmartPointer<vtkIntArray>::New (); nodePublicFlags->SetName ("publicFlags"); auto nodePrivateFlags = vtkSmartPointer<vtkIntArray>::New (); nodePrivateFlags->SetName ("privateFlags"); auto nodeErrorFlags = vtkSmartPointer<vtkIntArray>::New (); nodeErrorFlags->SetName ("errorFlags"); auto nodeNumber = vtkSmartPointer<vtkIntArray>::New (); nodeNumber->SetName ("nodeNumber"); auto nodeBorderConditionId = vtkSmartPointer<vtkIntArray>::New (); nodeBorderConditionId->SetName ("borderConditionId"); auto nodeContactConditionId = vtkSmartPointer<vtkIntArray>::New(); nodeContactConditionId->SetName("contactState"); auto contactDestroyed = vtkSmartPointer<vtkIntArray>::New(); contactDestroyed->SetName("failedContacts"); auto nodeDestroyed = vtkSmartPointer<vtkIntArray>::New(); nodeDestroyed->SetName("failedNodes"); auto nodeFailureMeasure = vtkSmartPointer<vtkDoubleArray>::New(); nodeFailureMeasure->SetName("failureMeasure"); float _norm[3]; dumpMeshSpecificData(_mesh, grid, points); for (auto it = MeshNodeIterator<MeshType, snapshotterId>(_mesh); it.hasNext(); it++) { auto& node = *it; border->InsertNextValue(node.isBorder() ? 1 : 0); used->InsertNextValue(node.isUsed() ? 1 : 0); contact->InsertNextValue(node.isInContact() ? 1 : 0); if (node.isUsed() && node.isBorder()) _mesh->findBorderNodeNormal(node, _norm, _norm+1, _norm+2, false); else _norm[0] = _norm[1] = _norm[2] = 0.0; norm->InsertNextTuple(_norm); vel->InsertNextTuple(node.velocity); crack->InsertNextTuple(node.getCrackDirection().coords); sxx->InsertNextValue(node.sxx); sxy->InsertNextValue(node.sxy); sxz->InsertNextValue(node.sxz); syy->InsertNextValue(node.syy); syz->InsertNextValue(node.syz); szz->InsertNextValue(node.szz); compression->InsertNextValue(node.getCompression()); tension->InsertNextValue(node.getTension()); shear->InsertNextValue(node.getShear()); deviator->InsertNextValue(node.getDeviator()); matId->InsertNextValue(node.getMaterialId()); rho->InsertNextValue(node.getRho()); mpiState->InsertNextValue(node.isRemote() ? 1 : 0); nodePrivateFlags->InsertNextValue (node.getPrivateFlags()); nodePublicFlags->InsertNextValue (node.getPublicFlags()); nodeErrorFlags->InsertNextValue (node.getErrorFlags()); nodeBorderConditionId->InsertNextValue (node.getBorderConditionId()); nodeContactConditionId->InsertNextValue(node.getContactConditionId()); nodeNumber->InsertNextValue(node.number); contactDestroyed->InsertNextValue(node.isContactDestroyed() ? 1 : 0); nodeDestroyed->InsertNextValue(node.isDestroyed() ? 1 : 0); nodeFailureMeasure->InsertNextValue(node.getDamageMeasure()); } vtkFieldData* fd; if (useCells) fd = grid->GetCellData(); else fd = grid->GetPointData(); grid->SetPoints(points); fd->AddArray(contact); fd->AddArray(border); fd->AddArray(used); fd->AddArray(norm); fd->AddArray(crack); fd->AddArray(sxx); fd->AddArray(sxy); fd->AddArray(sxz); fd->AddArray(syy); fd->AddArray(syz); fd->AddArray(szz); fd->AddArray(compression); fd->AddArray(tension); fd->AddArray(shear); fd->AddArray(deviator); fd->AddArray(matId); fd->AddArray(rho); fd->AddArray(mpiState); fd->AddArray (nodePrivateFlags); fd->AddArray (nodePublicFlags); fd->AddArray (nodeErrorFlags); fd->AddArray (nodeBorderConditionId); fd->AddArray (nodeContactConditionId); fd->AddArray(vel); fd->AddArray(nodeNumber); fd->AddArray(contactDestroyed); fd->AddArray(nodeDestroyed); fd->AddArray(nodeFailureMeasure); // Write file auto writer = vtkSmartPointer<GridWriterType>::New(); writer->SetFileName(fileName.c_str()); #ifdef CONFIG_VTK_5 writer->SetInput(grid); #else writer->SetInputData(grid); #endif writer->Write(); return fileName; }
void mitk::BoundingShapeVtkMapper2D::GenerateDataForRenderer(BaseRenderer *renderer) { const DataNode::Pointer node = GetDataNode(); if (node == nullptr) return; LocalStorage *localStorage = m_Impl->LocalStorageHandler.GetLocalStorage(renderer); // either update if GeometryData was modified or if the zooming was performed bool needGenerateData = localStorage->IsUpdateRequired( renderer, this, GetDataNode()); // true; // localStorage->GetLastGenerateDataTime() < node->GetMTime() || // localStorage->GetLastGenerateDataTime() < node->GetData()->GetMTime(); // //localStorage->IsGenerateDataRequired(renderer, this, GetDataNode()); double scale = renderer->GetScaleFactorMMPerDisplayUnit(); if (std::abs(scale - localStorage->m_ZoomFactor) > 0.001) { localStorage->m_ZoomFactor = scale; needGenerateData = true; } if (needGenerateData) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if (!visible) { localStorage->m_Actor->VisibilityOff(); return; } GeometryData::Pointer shape = static_cast<GeometryData *>(node->GetData()); if (shape == nullptr) return; mitk::BaseGeometry::Pointer geometry = shape->GetGeometry(); mitk::Vector3D spacing = geometry->GetSpacing(); // calculate cornerpoints and extent from geometry with visualization offset std::vector<Point3D> cornerPoints = GetCornerPoints(geometry, true); Point3D p0 = cornerPoints[0]; Point3D p1 = cornerPoints[1]; Point3D p2 = cornerPoints[2]; Point3D p4 = cornerPoints[4]; Point3D extent; extent[0] = sqrt((p0[0] - p4[0]) * (p0[0] - p4[0]) + (p0[1] - p4[1]) * (p0[1] - p4[1]) + (p0[2] - p4[2]) * (p0[2] - p4[2])); extent[1] = sqrt((p0[0] - p2[0]) * (p0[0] - p2[0]) + (p0[1] - p2[1]) * (p0[1] - p2[1]) + (p0[2] - p2[2]) * (p0[2] - p2[2])); extent[2] = sqrt((p0[0] - p1[0]) * (p0[0] - p1[0]) + (p0[1] - p1[1]) * (p0[1] - p1[1]) + (p0[2] - p1[2]) * (p0[2] - p1[2])); // calculate center based on half way of the distance between two opposing cornerpoints mitk::Point3D center = CalcAvgPoint(cornerPoints[7], cornerPoints[0]); if (m_Impl->HandlePropertyList.size() == 6) { // set handle positions Point3D pointLeft = CalcAvgPoint(cornerPoints[5], cornerPoints[6]); Point3D pointRight = CalcAvgPoint(cornerPoints[1], cornerPoints[2]); Point3D pointTop = CalcAvgPoint(cornerPoints[0], cornerPoints[6]); Point3D pointBottom = CalcAvgPoint(cornerPoints[7], cornerPoints[1]); Point3D pointFront = CalcAvgPoint(cornerPoints[2], cornerPoints[7]); Point3D pointBack = CalcAvgPoint(cornerPoints[4], cornerPoints[1]); m_Impl->HandlePropertyList[0].SetPosition(pointLeft); m_Impl->HandlePropertyList[1].SetPosition(pointRight); m_Impl->HandlePropertyList[2].SetPosition(pointTop); m_Impl->HandlePropertyList[3].SetPosition(pointBottom); m_Impl->HandlePropertyList[4].SetPosition(pointFront); m_Impl->HandlePropertyList[5].SetPosition(pointBack); } // caculate face normals double result0[3], result1[3], result2[3]; double a[3], b[3]; a[0] = (cornerPoints[5][0] - cornerPoints[6][0]); a[1] = (cornerPoints[5][1] - cornerPoints[6][1]); a[2] = (cornerPoints[5][2] - cornerPoints[6][2]); b[0] = (cornerPoints[5][0] - cornerPoints[4][0]); b[1] = (cornerPoints[5][1] - cornerPoints[4][1]); b[2] = (cornerPoints[5][2] - cornerPoints[4][2]); vtkMath::Cross(a, b, result0); a[0] = (cornerPoints[0][0] - cornerPoints[6][0]); a[1] = (cornerPoints[0][1] - cornerPoints[6][1]); a[2] = (cornerPoints[0][2] - cornerPoints[6][2]); b[0] = (cornerPoints[0][0] - cornerPoints[2][0]); b[1] = (cornerPoints[0][1] - cornerPoints[2][1]); b[2] = (cornerPoints[0][2] - cornerPoints[2][2]); vtkMath::Cross(a, b, result1); a[0] = (cornerPoints[2][0] - cornerPoints[7][0]); a[1] = (cornerPoints[2][1] - cornerPoints[7][1]); a[2] = (cornerPoints[2][2] - cornerPoints[7][2]); b[0] = (cornerPoints[2][0] - cornerPoints[6][0]); b[1] = (cornerPoints[2][1] - cornerPoints[6][1]); b[2] = (cornerPoints[2][2] - cornerPoints[6][2]); vtkMath::Cross(a, b, result2); vtkMath::Normalize(result0); vtkMath::Normalize(result1); vtkMath::Normalize(result2); // create cube for rendering bounding box auto cube = vtkCubeSource::New(); cube->SetXLength(extent[0] / spacing[0]); cube->SetYLength(extent[1] / spacing[1]); cube->SetZLength(extent[2] / spacing[2]); // calculates translation based on offset+extent not on the transformation matrix vtkSmartPointer<vtkMatrix4x4> imageTransform = geometry->GetVtkTransform()->GetMatrix(); auto translation = vtkSmartPointer<vtkTransform>::New(); translation->Translate(center[0] - imageTransform->GetElement(0, 3), center[1] - imageTransform->GetElement(1, 3), center[2] - imageTransform->GetElement(2, 3)); auto transform = vtkSmartPointer<vtkTransform>::New(); transform->SetMatrix(imageTransform); transform->PostMultiply(); transform->Concatenate(translation); transform->Update(); cube->Update(); auto transformFilter = vtkSmartPointer<vtkTransformFilter>::New(); transformFilter->SetInputData(cube->GetOutput()); transformFilter->SetTransform(transform); transformFilter->Update(); cube->Delete(); vtkSmartPointer<vtkPolyData> polydata = transformFilter->GetPolyDataOutput(); if (polydata == nullptr || (polydata->GetNumberOfPoints() < 1)) { localStorage->m_Actor->VisibilityOff(); localStorage->m_HandleActor->VisibilityOff(); localStorage->m_SelectedHandleActor->VisibilityOff(); return; } // estimate current image plane to decide whether the cube is visible or not const PlaneGeometry *planeGeometry = renderer->GetCurrentWorldPlaneGeometry(); if ((planeGeometry == nullptr) || (!planeGeometry->IsValid()) || (!planeGeometry->HasReferenceGeometry())) return; double origin[3]; origin[0] = planeGeometry->GetOrigin()[0]; origin[1] = planeGeometry->GetOrigin()[1]; origin[2] = planeGeometry->GetOrigin()[2]; double normal[3]; normal[0] = planeGeometry->GetNormal()[0]; normal[1] = planeGeometry->GetNormal()[1]; normal[2] = planeGeometry->GetNormal()[2]; // MITK_INFO << "normal1 " << normal[0] << " " << normal[1] << " " << normal[2]; localStorage->m_CuttingPlane->SetOrigin(origin); localStorage->m_CuttingPlane->SetNormal(normal); // add cube polydata to local storage localStorage->m_Cutter->SetInputData(polydata); localStorage->m_Cutter->SetGenerateCutScalars(1); localStorage->m_Cutter->Update(); if (localStorage->m_PropAssembly->GetParts()->IsItemPresent(localStorage->m_HandleActor)) localStorage->m_PropAssembly->RemovePart(localStorage->m_HandleActor); if (localStorage->m_PropAssembly->GetParts()->IsItemPresent(localStorage->m_Actor)) localStorage->m_PropAssembly->RemovePart(localStorage->m_Actor); vtkCoordinate *tcoord = vtkCoordinate::New(); tcoord->SetCoordinateSystemToWorld(); localStorage->m_HandleMapper->SetTransformCoordinate(tcoord); tcoord->Delete(); if (localStorage->m_Cutter->GetOutput()->GetNumberOfPoints() > 0) // if plane is visible in the renderwindow { mitk::DoubleProperty::Pointer handleSizeProperty = dynamic_cast<mitk::DoubleProperty *>(this->GetDataNode()->GetProperty("Bounding Shape.Handle Size Factor")); ScalarType initialHandleSize; if (handleSizeProperty != nullptr) initialHandleSize = handleSizeProperty->GetValue(); else initialHandleSize = 1.0 / 40.0; mitk::Point2D displaySize = renderer->GetDisplaySizeInMM(); double handleSize = ((displaySize[0] + displaySize[1]) / 2.0) * initialHandleSize; auto appendPoly = vtkSmartPointer<vtkAppendPolyData>::New(); unsigned int i = 0; // add handles and their assigned properties to the local storage mitk::IntProperty::Pointer activeHandleId = dynamic_cast<mitk::IntProperty *>(node->GetProperty("Bounding Shape.Active Handle ID")); bool visible = false; bool selected = false; for (auto handle : localStorage->m_Handles) { Point3D handleCenter = m_Impl->HandlePropertyList[i].GetPosition(); handle->SetRadius(handleSize); handle->SetCenter(handleCenter[0], handleCenter[1], handleCenter[2]); vtkMath::Normalize(normal); double angle = vtkMath::DegreesFromRadians(acos(vtkMath::Dot(normal, result0))); double angle1 = vtkMath::DegreesFromRadians(acos(vtkMath::Dot(normal, result1))); double angle2 = vtkMath::DegreesFromRadians(acos(vtkMath::Dot(normal, result2))); // show handles only if the corresponding face is aligned to the render window if ((((std::abs(angle - 0) < 0.001) || (std::abs(angle - 180) < 0.001)) && i != 0 && i != 1) || (((std::abs(angle1 - 0) < 0.001) || (std::abs(angle1 - 180) < 0.001)) && i != 2 && i != 3) || (((std::abs(angle2 - 0) < 0.001) || (std::abs(angle2 - 180) < 0.001)) && i != 4 && i != 5)) { if (activeHandleId == nullptr) { appendPoly->AddInputConnection(handle->GetOutputPort()); } else { if ((activeHandleId->GetValue() != m_Impl->HandlePropertyList[i].GetIndex())) { appendPoly->AddInputConnection(handle->GetOutputPort()); } else { handle->Update(); localStorage->m_SelectedHandleMapper->SetInputData(handle->GetOutput()); localStorage->m_SelectedHandleActor->VisibilityOn(); selected = true; } } visible = true; } i++; } if (visible) { appendPoly->Update(); } else { localStorage->m_HandleActor->VisibilityOff(); localStorage->m_SelectedHandleActor->VisibilityOff(); } auto stripper = vtkSmartPointer<vtkStripper>::New(); stripper->SetInputData(localStorage->m_Cutter->GetOutput()); stripper->Update(); auto cutPolyData = vtkSmartPointer<vtkPolyData>::New(); cutPolyData->SetPoints(stripper->GetOutput()->GetPoints()); cutPolyData->SetPolys(stripper->GetOutput()->GetLines()); localStorage->m_Actor->GetMapper()->SetInputDataObject(cutPolyData); mitk::ColorProperty::Pointer selectedColor = dynamic_cast<mitk::ColorProperty *>(node->GetProperty("color")); if (selectedColor != nullptr) { mitk::Color color = selectedColor->GetColor(); localStorage->m_Actor->GetProperty()->SetColor(color[0], color[1], color[2]); } if (activeHandleId != nullptr) { localStorage->m_HandleActor->GetProperty()->SetColor(1, 0, 0); } else { localStorage->m_HandleActor->GetProperty()->SetColor(1, 1, 1); } localStorage->m_HandleActor->GetMapper()->SetInputDataObject(appendPoly->GetOutput()); // add parts to the overall storage localStorage->m_PropAssembly->AddPart(localStorage->m_Actor); localStorage->m_PropAssembly->AddPart(localStorage->m_HandleActor); if (selected) { localStorage->m_PropAssembly->AddPart(localStorage->m_SelectedHandleActor); } localStorage->m_PropAssembly->VisibilityOn(); localStorage->m_Actor->VisibilityOn(); localStorage->m_HandleActor->VisibilityOn(); } else { localStorage->m_PropAssembly->VisibilityOff(); localStorage->m_Actor->VisibilityOff(); localStorage->m_HandleActor->VisibilityOff(); localStorage->m_SelectedHandleActor->VisibilityOff(); localStorage->UpdateGenerateDataTime(); } localStorage->UpdateGenerateDataTime(); } }
int main(int argc, char ** argv) { QString volcR10("C:/develop/$sync/GFZ/data/VTK XML data/Volcano 2 topo.vtp"); auto object = Loader::readFile( volcR10 ); double bounds[6]; auto & dataSet = *object->dataSet(); dataSet.GetBounds(bounds); vtkVector2d A{ bounds[0], 0 }; vtkVector2d B{ bounds[1], 0 }; auto inputPolyData = dynamic_cast<PolyDataObject *>(object.get()); auto selector = vtkSmartPointer<LineOnCellsSelector2D>::New(); selector->SetInputData(&dataSet); selector->SetCellCentersConnection(inputPolyData->cellCentersOutputPort()); selector->SetStartPoint(A); selector->SetEndPoint(B); //auto extractSelection = vtkSmartPointer<vtkExtractSelectedPolyDataIds>::New(); //extractSelection->SetInputData(&dataSet); //extractSelection->SetInputConnection(1, selector->GetOutputPort()); //extractSelection->Update(); //auto vPoly = extractSelection->GetOutput(); //auto extractSelection = vtkSmartPointer<vtkExtractSelection>::New(); //extractSelection->SetInputData(&dataSet); //extractSelection->SetSelectionConnection(selector->GetOutputPort()); //extractSelection->Update(); //auto outputData = vtkUnstructuredGrid::SafeDownCast(extractSelection->GetOutput()); //auto vPoly = vtkSmartPointer<vtkPolyData>::New(); //vPoly->SetPoints(outputData->GetPoints()); //vPoly->SetPolys(outputData->GetCells()); //vPoly->GetCellData()->PassData(outputData->GetCellData()); //vPoly->GetPointData()->PassData(outputData->GetPointData()); selector->Update(); auto vPoly = selector->GetExtractedPoints(); auto poly = std::make_unique<PolyDataObject>("extraction", *vPoly); QApplication app(argc, argv); ColorMappingChooser cmc; cmc.show(); RenderConfigWidget rcw; rcw.show(); RendererConfigWidget rrcw; rrcw.show(); DataSetHandler dsh; DataMapping dm(dsh); auto view = dm.openInRenderView({ poly.get(), object.get() }); auto pointsVis = dynamic_cast<RenderedPolyData *>(view->visualizationFor(poly.get())); pointsVis->mainActor()->GetProperty()->SetPointSize(5); pointsVis->mainActor()->PickableOn(); auto baseVis = dynamic_cast<RenderedPolyData *>(view->visualizationFor(object.get())); baseVis->mainActor()->GetProperty()->SetOpacity(0.2); baseVis->mainActor()->PickableOff(); view->show(); cmc.setCurrentRenderView(view); rcw.setCurrentRenderView(view); rcw.setSelectedData(poly.get()); rrcw.setCurrentRenderView(view); return app.exec(); }
void PickCallbackFunction(vtkObject* caller, long unsigned int vtkNotUsed(eventId), void* clientData, void* vtkNotUsed(callData)) { vtkAreaPicker *areaPicker = static_cast<vtkAreaPicker*>(caller); iARenderer *ren = static_cast<iARenderer*>(clientData); ren->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor(ren->selectedActor); auto extractSelection = vtkSmartPointer<vtkExtractSelectedFrustum>::New(); extractSelection->SetInputData(0, ren->getRenderObserver()->GetImageData()); extractSelection->PreserveTopologyOff(); extractSelection->SetFrustum(areaPicker->GetFrustum()); extractSelection->Update(); if (!extractSelection->GetOutput()->GetNumberOfElements(vtkUnstructuredGrid::CELL)) { ren->emitNoSelectedCells(); return; } if (ren->GetInteractor()->GetControlKey() && !ren->GetInteractor()->GetShiftKey()) { // Adds cells to selection auto append = vtkSmartPointer<vtkAppendFilter>::New(); append->AddInputData(ren->finalSelection); append->AddInputData(extractSelection->GetOutput()); append->Update(); ren->finalSelection->ShallowCopy(append->GetOutput()); } else if (ren->GetInteractor()->GetControlKey() && ren->GetInteractor()->GetShiftKey()) { // Removes cells from selection auto newfinalSel = vtkSmartPointer<vtkUnstructuredGrid>::New(); newfinalSel->Allocate(1, 1); newfinalSel->SetPoints(ren->finalSelection->GetPoints()); auto currSel = vtkSmartPointer<vtkUnstructuredGrid>::New(); currSel->ShallowCopy(extractSelection->GetOutput()); double f_Cell[DIM] = { 0,0,0 }, c_Cell[DIM] = { 0,0,0 }; double* spacing = ren->getRenderObserver()->GetImageData()->GetSpacing(); for (vtkIdType i = 0; i < ren->finalSelection->GetNumberOfCells(); ++i) { bool addCell = true; GetCellCenter(ren->finalSelection, i, f_Cell, spacing); for (vtkIdType j = 0; j < currSel->GetNumberOfCells(); ++j) { GetCellCenter(currSel, j, c_Cell, spacing); if (f_Cell[0] == c_Cell[0] && f_Cell[1] == c_Cell[1] && f_Cell[2] == c_Cell[2]) { addCell = false; break; } } if (addCell) newfinalSel->InsertNextCell(ren->finalSelection->GetCell(i)->GetCellType(), ren->finalSelection->GetCell(i)->GetPointIds()); } ren->finalSelection->ShallowCopy(newfinalSel); } else { // New selection ren->finalSelection->ShallowCopy(extractSelection->GetOutput()); } ren->selectedMapper->Update(); ren->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->AddActor(ren->selectedActor); ren->emitSelectedCells(ren->finalSelection); }
bool Exporter::exportImageFormat(ImageDataObject & image, const QString & fileName) { QString ext = QFileInfo(fileName).suffix().toLower(); vtkSmartPointer<vtkImageWriter> writer; if (ext == "png") { writer = vtkSmartPointer<vtkPNGWriter>::New(); } else if (ext == "jpg" || ext == "jpeg") { writer = vtkSmartPointer<vtkJPEGWriter>::New(); } else if (ext == "bmp") { writer = vtkSmartPointer<vtkBMPWriter>::New(); } if (!writer) { return false; } const auto scalars = image.dataSet()->GetPointData()->GetScalars(); if (!scalars) { return false; } const auto components = scalars->GetNumberOfComponents(); if (components != 1 && components != 3 && components != 4) { return false; } if (scalars->GetDataType() == VTK_UNSIGNED_CHAR) { writer->SetInputData(image.dataSet()); } else { auto toUChar = vtkSmartPointer<ImageMapToColors>::New(); toUChar->SetInputData(image.dataSet()); auto lut = vtkSmartPointer<vtkLookupTable>::New(); lut->SetNumberOfTableValues(0xFF); lut->SetHueRange(0, 0); lut->SetSaturationRange(0, 0); lut->SetValueRange(0, 1); ValueRange<> totalRange; for (int c = 0; c < components; ++c) { ValueRange<> range; scalars->GetRange(range.data(), c); totalRange.add(range); } toUChar->SetOutputFormat( components == 3 ? VTK_RGB : (components == 4 ? VTK_RGBA : VTK_LUMINANCE)); toUChar->SetLookupTable(lut); writer->SetInputConnection(toUChar->GetOutputPort()); } writer->SetFileName(fileName.toUtf8().data()); writer->Write(); return true; }