Skip to content

PolygonIntersection

vtk-examples/Cxx/GeometricObjects/PolygonIntersection

Other languages

See (Python), (CSharp)

Question

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

Code

PolygonIntersection.cxx

#include <vtkNew.h>
#include <vtkPoints.h>
#include <vtkPolygon.h>

int main(int, char*[])
{
  // Create a square in the XY plane
  vtkNew<vtkPoints> points;
  points->InsertNextPoint(0.0, 0.0, 0.0);
  points->InsertNextPoint(1.0, 0.0, 0.0);
  points->InsertNextPoint(1.0, 1.0, 0.0);
  points->InsertNextPoint(0.0, 1.0, 0.0);

  // Create the polygon
  vtkNew<vtkPolygon> polygon;
  polygon->GetPoints()->DeepCopy(points);
  polygon->GetPointIds()->SetNumberOfIds(4); // 4 corners of the square
  polygon->GetPointIds()->SetId(0, 0);
  polygon->GetPointIds()->SetId(1, 1);
  polygon->GetPointIds()->SetId(2, 2);
  polygon->GetPointIds()->SetId(3, 3);

  // Inputs
  double p1[3] = {0.1, 0, -1.0};
  double p2[3] = {0.1, 0, 1.0};
  double tolerance = 0.001;
  // Outputs
  double t; // Parametric coordinate of intersection (0 (corresponding to p1) to
            // 1 (corresponding to p2))
  double x[3]; // The coordinate of the intersection
  double pcoords[3];
  int subId;

  vtkIdType iD =
      polygon->IntersectWithLine(p1, p2, tolerance, t, x, pcoords, subId);

  auto res = (iD == 1) ? "Yes" : "No";
  std::cout << "intersected? " << res << std::endl;
  std::cout << "intersection: " << x[0] << " " << x[1] << " " << x[2]
            << std::endl;

  return EXIT_SUCCESS;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.12 FATAL_ERROR)

project(PolygonIntersection)

find_package(VTK COMPONENTS 
  CommonCore
  CommonDataModel
)

if (NOT VTK_FOUND)
  message(FATAL_ERROR "PolygonIntersection: 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(PolygonIntersection MACOSX_BUNDLE PolygonIntersection.cxx )
  target_link_libraries(PolygonIntersection PRIVATE ${VTK_LIBRARIES}
)
# vtk_module_autoinit is needed
vtk_module_autoinit(
  TARGETS PolygonIntersection
  MODULES ${VTK_LIBRARIES}
)

Download and Build PolygonIntersection

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

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

./PolygonIntersection

WINDOWS USERS

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