Skip to content

CellTreeLocator

vtk-examples/Cxx/PolyData/CellTreeLocator

Question

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

Code

CellTreeLocator.cxx

#include <vtkCellTreeLocator.h>
#include <vtkGenericCell.h>
#include <vtkNew.h>
#include <vtkPolyData.h>
#include <vtkSphereSource.h>
#include <vtkUnstructuredGrid.h>

int main(int, char*[])
{
  vtkNew<vtkSphereSource> sphereSource;
  sphereSource->SetCenter(0.0, 0.0, 0.0);
  sphereSource->SetRadius(1.0);
  sphereSource->Update();

  // Create the tree
  vtkNew<vtkCellTreeLocator> cellTree;
  cellTree->SetDataSet(sphereSource->GetOutput());
  cellTree->BuildLocator();

  double testInside[3] = {0.5, 0.0, 0.0};
  double testOutside[3] = {10.0, 0.0, 0.0};

  double pcoords[3], weights[3];

  vtkIdType cellId;

  vtkNew<vtkGenericCell> cell;

  int returnValue = EXIT_SUCCESS;

  // Should be inside
  cellId = cellTree->FindCell(testInside, 0, cell, pcoords, weights);
  if (cellId >= 0)
  {
    std::cout << "First point: in cell " << cellId << std::endl;
  }
  else
  {
    std::cout << "ERROR: Cell was not found but should have been." << std::endl;
    returnValue = EXIT_FAILURE;
  }

  // Should be outside
  cellId = cellTree->FindCell(testOutside, 0, cell, pcoords, weights);
  if (cellId >= 0)
  {
    std::cout << "ERROR: Found point in cell " << cellId
              << " but it should be outside the domain." << std::endl;
    returnValue = EXIT_FAILURE;
  }
  else
  {
    std::cout << "Second point: outside" << std::endl;
  }

  return returnValue;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.3 FATAL_ERROR)

project(CellTreeLocator)

find_package(VTK COMPONENTS 
  vtkCommonCore
  vtkCommonDataModel
  vtkFiltersGeneral
  vtkFiltersSources
  QUIET
)

if (NOT VTK_FOUND)
  message("Skipping CellTreeLocator: ${VTK_NOT_FOUND_MESSAGE}")
  return ()
endif()
message (STATUS "VTK_VERSION: ${VTK_VERSION}")
if (VTK_VERSION VERSION_LESS "8.90.0")
  # old system
  include(${VTK_USE_FILE})
  add_executable(CellTreeLocator MACOSX_BUNDLE CellTreeLocator.cxx )
  target_link_libraries(CellTreeLocator PRIVATE ${VTK_LIBRARIES})
else ()
  # include all components
  add_executable(CellTreeLocator MACOSX_BUNDLE CellTreeLocator.cxx )
  target_link_libraries(CellTreeLocator PRIVATE ${VTK_LIBRARIES})
  # vtk_module_autoinit is needed
  vtk_module_autoinit(
    TARGETS CellTreeLocator
    MODULES ${VTK_LIBRARIES}
    )
endif ()

Download and Build CellTreeLocator

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

cd CellTreeLocator/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:

./CellTreeLocator

WINDOWS USERS

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