Read a VTP file

From KitwarePublic
Jump to: navigation, search

As VTP is a very flexible format, there is no way to make a generic reader. You must read the data that you are interested in. A generic reader can only look for points and triangles.

#include <iostream>
#include <vector>
 
#include "vtkCellArray.h"
#include "vtkPoints.h"
#include "vtkXMLPolyDataReader.h"
#include "vtkPolyData.h"
 
struct Point
{
	double x,y,z;
	Point(const double xin, const double yin, const double zin) : x(xin), y(yin), z(zin) {}
};
 
int main()
{		
	//get all data from the file
	vtkXMLPolyDataReader* reader = vtkXMLPolyDataReader::New();
	reader->SetFileName("Triangle.vtp");
	reader->Update();
	vtkPolyData* polydata = reader->GetOutput();
 
	//get the number of points the file contains
	vtkIdType NumPoints = polydata->GetNumberOfPoints();
 
	//if there are no points, quit
	if(!(NumPoints > 0) )
	{
		exit(-1);
	}
 
	//read in all of the points
	std::vector<Point> Points;
	double point[3];
	for(vtkIdType i = 0; i < NumPoints; i++)
	{
		polydata->GetPoint(i, point);
		Points.push_back(Point(point[0], point[1], point[2]));
	}
 
	//get the triangles (if there are any)
	std::vector<std::vector<int> > VertexLists;
	vtkIdType NumPolys = polydata->GetNumberOfPolys();
	if(NumPolys > 0)
	{
		vtkCellArray* TriangleCells = polydata->GetPolys();
		vtkIdType npts;
		vtkIdType *pts;
 
		while(TriangleCells->GetNextCell(npts, pts))
		{
			std::vector<int> List(3);
			List[0] = pts[0];
			List[1] = pts[1];
			List[2] = pts[2];
 
			VertexLists.push_back(List);
		}	
	}
 
	std::cout << "Points: " << Points.size() << std::endl;
	for(unsigned int i = 0; i < Points.size(); i++)
	{
		std::cout << Points[i].x << " " << Points[i].y << " " << Points[i].z << std::endl;
	}
 
	std::cout << std::endl;
 
	std::cout << "Triangles: " << VertexLists.size() << std::endl;
	for(unsigned int i = 0; i < VertexLists.size(); i++)
	{
		std::cout << VertexLists[i][0] << " " << VertexLists[i][1] << " " << VertexLists[i][2] << std::endl;
	}
	return 0;
}