wiki:cypress/Example VTK-C++
// VTK Structured Grid Sample
//
// Created on Sun Mar 23 11:17:34 2014
//
//
#include <iostream>
#include <fstream>
#include <vtkXMLStructuredGridWriter.h>
#include <vtkStructuredGrid.h>
#include <vtkDataSet.h>
#include <vtkPointData.h>
#include <vtkCellData.h>
#include <vtkCellArray.h>
#include <vtkDoubleArray.h>

int main(int argc, char **argv) {
        // Declare "ifsteam" class object
        ifstream ifile;

        // Open a file with read-mode (default) "open" is a member function of "ifstream"
        ifile.open("officeFlow.txt");
        // Check if file exists
        if (ifile.fail()) {
                std::cout << "file not found" << endl;
                return 0;
        }

        // Reading data from the file. ">>" is a operator of "ifstream"
        int nx, ny, nz;
        ifile >> nx >> ny >> nz;

        // setup VTK
        vtkXMLStructuredGridWriter *writer = vtkXMLStructuredGridWriter::New();
        vtkStructuredGrid *structured_grid = vtkStructuredGrid::New();
        structured_grid->SetDimensions(nx, ny, nz);
        vtkPoints *nodes = vtkPoints::New();
        nodes->Allocate(nx * ny * nz);
        vtkDoubleArray* prsArray = vtkDoubleArray::New();
        prsArray->SetNumberOfComponents(1);
        prsArray->SetName("Pressure");
        vtkDoubleArray* velArray = vtkDoubleArray::New();
        velArray->SetNumberOfComponents(3);
        velArray->SetName("Velocity");

        for (int k = 0; k < nz; k++) {
                for (int j = 0; j < ny; j++) {
                        for (int i = 0; i < nx; i++) {
                                double x, y, z, u, v, w, p;
                                ifile >> x >> y >> z >> u >> v >> w >> p;

                                nodes->InsertNextPoint(x, y, z);
                                prsArray->InsertNextTuple(&p);
                                velArray->InsertNextTuple3(u, v, w);
                        }
                }
        }
        // close file
        ifile.close();

        structured_grid->SetPoints(nodes);
        structured_grid->GetPointData()->AddArray(velArray);
        structured_grid->GetPointData()->AddArray(prsArray);

#if (VTK_MAJOR_VERSION >=6)
        writer->SetInputData(structured_grid);
#else
        writer->SetInput(structured_grid);
#endif

        writer->SetFileName("officeFlow.vts");
        writer->SetDataModeToAscii();
        writer->Write();

        structured_grid->Delete();
        writer->Delete();
        nodes->Delete();
        velArray->Delete();
        prsArray->Delete();
}

Compile

$ cmake .
$ make
Last modified 4 years ago Last modified on Aug 20, 2015 8:33:03 PM