Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save daviddoria/8bf981aa593b7cefcd9114588e4766db to your computer and use it in GitHub Desktop.
Save daviddoria/8bf981aa593b7cefcd9114588e4766db to your computer and use it in GitHub Desktop.
#include <vtkCellData.h>
#include <vtkSmartPointer.h>
#include <vtkStructuredGrid.h>
#include <vtkUnsignedIntArray.h>
#include <vtkXMLStructuredGridWriter.h>
void Grid3D() {
// Create a grid
vtkSmartPointer<vtkStructuredGrid> structuredGrid =
vtkSmartPointer<vtkStructuredGrid>::New();
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
// Create a vtkUnsignedCharArray container and store the colors in it
vtkSmartPointer<vtkUnsignedIntArray> labels =
vtkSmartPointer<vtkUnsignedIntArray>::New();
labels->SetName("Labels");
labels->SetNumberOfComponents(1);
unsigned int voxelsPerDimension = 2;
unsigned int counter = 0;
// The grid is created as points (the corners of voxels), so we need n+1
// points per dimension
for (unsigned int k = 0; k < voxelsPerDimension + 1; k++) {
for (unsigned int j = 0; j < voxelsPerDimension + 1; j++) {
for (unsigned int i = 0; i < voxelsPerDimension + 1; i++) {
points->InsertNextPoint(i, j, k);
}
}
}
// raster scan label voxels
unsigned int voxelCounter = 0;
for (unsigned int k = 0; k < voxelsPerDimension; k++) {
for (unsigned int j = 0; j < voxelsPerDimension; j++) {
for (unsigned int i = 0; i < voxelsPerDimension; i++) {
labels->InsertNextValue(voxelCounter);
voxelCounter++;
}
}
}
structuredGrid->GetCellData()->SetScalars(labels);
// Specify the dimensions of the grid (again, in their points)
structuredGrid->SetDimensions(voxelsPerDimension + 1, voxelsPerDimension + 1,
voxelsPerDimension + 1);
structuredGrid->SetPoints(points);
structuredGrid->BlankPoint(0);
structuredGrid->Modified();
vtkSmartPointer<vtkXMLStructuredGridWriter> structuredGridWriter =
vtkXMLStructuredGridWriter::New();
structuredGridWriter->SetInputData(structuredGrid);
structuredGridWriter->SetFileName("grid.vts");
structuredGridWriter->Write();
}
int main(int, char *[]) {
Grid3D();
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment