wiki:cypress/Example VTK-C++

Version 2 (modified by fuji, 9 years ago) ( diff )

// 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
Note: See TracWiki for help on using the wiki.