Skip to content

CellIdFromGridCoordinates

Repository source: CellIdFromGridCoordinates

Question

If you have a question about this example, please use the VTK Discourse Forum

Code

CellIdFromGridCoordinates.cxx

#include <vtkImageData.h>
#include <vtkNew.h>
#include <vtkStructuredData.h>

int main(int, char*[])
{

  vtkNew<vtkImageData> grid;
  grid->SetOrigin(0, 0, 0);

  unsigned int numVoxelsPerDimension =
      2; // the number of voxels in each dimension
  grid->SetSpacing(1, 1, 1);

  int extent[6];
  extent[0] = 0;
  extent[1] = numVoxelsPerDimension;
  extent[2] = 0;
  extent[3] = numVoxelsPerDimension;
  extent[4] = 0;
  extent[5] = numVoxelsPerDimension;
  grid->SetExtent(extent);
  grid->AllocateScalars(VTK_INT, 1);

  for (unsigned int i = 0; i < numVoxelsPerDimension; ++i)
  {
    for (unsigned int j = 0; j < numVoxelsPerDimension; ++j)
    {
      for (unsigned int k = 0; k < numVoxelsPerDimension; ++k)
      {
        int pos[3];
        pos[0] = i;
        pos[1] = j;
        pos[2] = k;

        vtkIdType id = vtkStructuredData::ComputeCellIdForExtent(extent, pos);
        std::cout << "Cell " << i << " " << j << " " << k << " has id : " << id
                  << std::endl;
      }
    }
  }

  return EXIT_SUCCESS;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.12 FATAL_ERROR)

project(CellIdFromGridCoordinates)

find_package(VTK COMPONENTS 
  CommonCore
  CommonDataModel
)

if (NOT VTK_FOUND)
  message(FATAL_ERROR "CellIdFromGridCoordinates: Unable to find the VTK build folder.")
endif()

# Prevent a "command line is too long" failure in Windows.
set(CMAKE_NINJA_FORCE_RESPONSE_FILE "ON" CACHE BOOL "Force Ninja to use response files.")
add_executable(CellIdFromGridCoordinates MACOSX_BUNDLE CellIdFromGridCoordinates.cxx )
  target_link_libraries(CellIdFromGridCoordinates PRIVATE ${VTK_LIBRARIES}
)
# vtk_module_autoinit is needed
vtk_module_autoinit(
  TARGETS CellIdFromGridCoordinates
  MODULES ${VTK_LIBRARIES}
)

Download and Build CellIdFromGridCoordinates

Click here to download CellIdFromGridCoordinates and its CMakeLists.txt file. Once the tarball CellIdFromGridCoordinates.tar has been downloaded and extracted,

cd CellIdFromGridCoordinates/build

If VTK is installed:

cmake ..

If VTK is not installed but compiled on your system, you will need to specify the path to your VTK build:

cmake -DVTK_DIR:PATH=/home/me/vtk_build ..

Build the project:

make

and run it:

./CellIdFromGridCoordinates

WINDOWS USERS

Be sure to add the VTK bin directory to your path. This will resolve the VTK dll's at run time.