Write a VTP file
<source lang="cpp"> bool VtpWrite(ModelClass &Model, const string &Filename) { if(Model.Colors.size() == 0) { for(unsigned int i = 0; i < Model.Points.size(); i++) Model.Colors.push_back(Red()); }
vtkSmartPointer<vtkPoints> points3D = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkCellArray> Vertices = vtkSmartPointer<vtkCellArray>::New();
for ( unsigned int i = 0; i < Model.Points.size(); ++i ) { vtkIdType pid[1]; Point P = Model.Points[i]; pid[0] = points3D->InsertNextPoint(P.x, P.y, P.z); Vertices->InsertNextCell(1,pid); }
vtkSmartPointer<vtkUnsignedCharArray> Colors = vtkSmartPointer<vtkUnsignedCharArray>::New();
Colors->SetNumberOfComponents(3); Colors->SetName("Colors");
for ( unsigned int i = 0; i < Model.Colors.size(); ++i ) { Color Color = Model.Colors[i]; unsigned char ColorArray[3]; CharArray(Color, ColorArray); Colors->InsertNextTupleValue(ColorArray); }
bool HasTriangles; if(Model.VertexList.size() > 0) HasTriangles = true; else HasTriangles = false;
vtkSmartPointer<vtkCellArray> triangles = vtkSmartPointer<vtkCellArray>::New(); if(HasTriangles) { for(unsigned int i = 0; i < Model.VertexList.size(); i++) { vector<int> vlist = Model.VertexList[i]; vtkSmartPointer<vtkTriangle> triangle = vtkSmartPointer<vtkTriangle>::New(); triangle->GetPointIds()->SetId(0,vlist[0]); triangle->GetPointIds()->SetId(1,vlist[1]); triangle->GetPointIds()->SetId(2,vlist[2]); triangles->InsertNextCell(triangle); } }
vtkSmartPointer<vtkPolyData> polydata = vtkPolyData::New();
polydata->SetPoints(points3D); polydata->SetVerts(Vertices);
if(HasTriangles) polydata->SetPolys(triangles);
polydata->GetPointData()->SetVectors(Colors);
vtkSmartPointer<vtkXMLPolyDataWriter> writer = vtkSmartPointer<vtkXMLPolyDataWriter>::New(); writer->SetFileName(Filename.c_str()); writer->SetInput(polydata); writer->Write();
cout << "Finished writing vtp file " << Filename << "." << endl; cout << "NumPoints: " << Model.Points.size() << endl; cout << "NumColors: " << Model.Colors.size() << endl;
return true;//write finshed ok } </source>