Skip to content

VisualizeKDTree

Repository source: VisualizeKDTree


Description

This demo displays the levels of a vtkKdTree using a slider. A KdTree is an k-d tree. It is used in fast intersection tests, collision detection and point location.

Here's the embedded video:

a

Other languages

See (PythonicAPI), (Java)

Question

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

Code

VisualizeKDTree.cxx

#include <vtkActor.h>
#include <vtkCommand.h>
#include <vtkInteractorStyleTrackballCamera.h>
#include <vtkKdTree.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkProperty2D.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSliderRepresentation2D.h>
#include <vtkSliderWidget.h>
#include <vtkTextProperty.h>

// Readers
#include <vtkBYUReader.h>
#include <vtkOBJReader.h>
#include <vtkPLYReader.h>
#include <vtkPolyDataReader.h>
#include <vtkSTLReader.h>
#include <vtkXMLPolyDataReader.h>

#include <vtkSphereSource.h>

#include <vtk_cli11.h>

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

namespace {
/**
 * @brief ReadPolyData
 *
 * If the path is empty, or the extension is unknown, a sphere is returned.
 * @param path: The path to the polydata.
 * @return
 */
vtkNew<vtkPolyData> ReadPolyData(fs::path const& path);

// #include <vtkCoordinate.h>

/**
 * @brief The Slider2DProperties struct.
 *
 * These are the default properties.
 * Instantiate the struct and modify as appropriate.
 *
 * @return The properties.
 */
struct Slider2DProperties
{
  struct _Colors
  {
    // The color of the text indicating what the slider controls.
    std::string titleColor{"White"};
    // The color of the text displaying the value.
    std::string labelColor{"White"};
    // The color of the knob that slides.
    std::string sliderColor{"White"};
    // The color of the bar.
    std::string barColor{"White"};
    // The color of the ends of the bar.
    std::string barEndsColor{"White"};
    // The color of the knob when the mouse is held on it.
    std::string selectedColor{"HotPink"};
  };

  struct _Dimensions
  {
    double tubeWidth{0.008};
    double sliderLength{0.01};
    double sliderWidth{0.02};
    double endCapLength{0.005};
    double endCapWidth{0.05};
    double titleHeight{0.03};
    double labelHeight{0.025};
  };

  struct _Position
  {
    int coordinateSystem = VTK_NORMALIZED_VIEWPORT;
    std::array<double, 2> point1{0.1, 0.1};
    std::array<double, 2> point2{0.9, 0.1};
  };

  struct _Range
  {
    double minimumValue{0.0};
    double maximumValue{1.0};
    double value{0.0};
  };

  struct _Text
  {
    // Font families are: Ariel, Courier and Times
    std::string title{};
    std::string titleFontFamily{"Arial"};
    bool titleBold{true};
    bool titleItalic{false};
    bool titleShadow{true};
    std::string labelFontFamily{"Arial"};
    bool labelBold{true};
    bool labelItalic{false};
    bool labelShadow{true};
  };

  struct _Colors Colors;
  struct _Dimensions Dimensions;
  struct _Position Position;
  struct _Range Range;
  struct _Text Text;
};

/**
 * @brief MakeSlider2DProperties
 *
 * This applies more specific values to the default Slider2DProperties.
 *
 * @return The slider 2D properties.
 */
Slider2DProperties MakeSlider2DProperties();

/**
 * @brief Make2DSliderWidget
 *
 * Make a 2D slider widget.
 *
 * @param properties The 2D slider properties.
 * @param iren The vtkInteractor.
 * @return The slider widget.
 */
vtkNew<vtkSliderWidget> Make2DSliderWidget(Slider2DProperties const& properties,
                                           vtkRenderWindowInteractor* iren);

class vtkSliderCallback : public vtkCommand
{
public:
  static vtkSliderCallback* New()
  {
    return new vtkSliderCallback;
  }
  vtkSliderCallback() : kdTree(0), polydata(0)
  {
  }

  virtual void Execute(vtkObject* caller, unsigned long, void*)
  {
    vtkSliderWidget* sliderWidget = reinterpret_cast<vtkSliderWidget*>(caller);
    auto level = static_cast<int>(vtkMath::Round(
        static_cast<vtkSliderRepresentation*>(sliderWidget->GetRepresentation())
            ->GetValue()));
    this->kdTree->GenerateRepresentation(level, this->polydata);
    sliderWidget->GetSliderRepresentation()->SetValue(level);
  }

  vtkKdTree* kdTree;
  vtkPolyData* polydata;
};
} // namespace

int main(int argc, char* argv[])
{
  CLI::App app{"Display the level of a vtkKDTree using a slider."
               "\nIf no filename is specified,a sphere is used."};

  // Define options
  std::string fileName{""};
  app.add_option("fileName", fileName,
                 "The path to the data file e.g. shark.ply.");

  CLI11_PARSE(app, argc, argv);

  auto path = fs::path(fileName);
  if (!path.empty())
  {
    if (!fs::is_regular_file(path))
    {
      std::cerr << "Unable to find: " << path << std::endl;
      return EXIT_FAILURE;
    }
  }

  vtkNew<vtkPolyData> polyData;
  if (fs::is_regular_file(path))
  {
    polyData = ReadPolyData(path);
  }
  else
  {
    // Default to a sphere if the path is empty.
    vtkNew<vtkSphereSource> source;
    source->SetPhiResolution(50);
    source->SetThetaResolution(50);
    source->Update();
    polyData->DeepCopy(source->GetOutput());
  }

  vtkNew<vtkNamedColors> colors;

  vtkNew<vtkPolyDataMapper> pointsMapper;
  pointsMapper->SetInputData(polyData);
  pointsMapper->ScalarVisibilityOff();

  vtkNew<vtkActor> pointsActor;
  pointsActor->SetMapper(pointsMapper);
  pointsActor->GetProperty()->SetColor(colors->GetColor4d("Yellow").GetData());
  pointsActor->GetProperty()->SetOpacity(0.3);
  pointsActor->GetProperty()->SetInterpolationToFlat();

  int maxLevel = 5;
  // Create the tree.
  vtkNew<vtkKdTree> kdTree;
  kdTree->SetDataSet(polyData);
  kdTree->SetMaxLevel(maxLevel);
  kdTree->BuildLocator();

  // Initialize the representation.
  vtkNew<vtkPolyData> polydata;
  kdTree->GenerateRepresentation(0, polydata);

  vtkNew<vtkPolyDataMapper> kdtreeMapper;
  kdtreeMapper->SetInputData(polydata);

  vtkNew<vtkActor> kdtreeActor;
  kdtreeActor->SetMapper(kdtreeMapper);
  kdtreeActor->GetProperty()->SetInterpolationToFlat();
  kdtreeActor->GetProperty()->SetOpacity(0.5);
  kdtreeActor->GetProperty()->EdgeVisibilityOn();
  kdtreeActor->GetProperty()->SetColor(
      colors->GetColor4d("SpringGreen").GetData());

  // A renderer and render window.
  vtkNew<vtkRenderer> ren;
  ren->SetBackground(colors->GetColor3d("MidnightBlue").GetData());
  // ren->UseDepthPeelingOn();
  ren->UseHiddenLineRemovalOn();
  vtkNew<vtkRenderWindow> renWin;
  auto appFn = fs::path((app.get_name())).stem().string();
  renWin->SetSize(600, 600);
  renWin->AddRenderer(ren);

  // An interactor.
  vtkNew<vtkInteractorStyleTrackballCamera> style;
  vtkNew<vtkRenderWindowInteractor> iren;
  iren->SetRenderWindow(renWin);
  iren->SetInteractorStyle(style);

  // Add the actors to the scene.
  ren->AddActor(pointsActor);
  ren->AddActor(kdtreeActor);

  // Render an image (lights and cameras are created automatically).
  renWin->Render();

  auto sp = MakeSlider2DProperties();
  sp.Range.minimumValue = 0;
  sp.Range.maximumValue = kdTree->GetMaxLevel();
  sp.Range.value = vtkMath::Round(kdTree->GetMaxLevel() / 2.0);

  sp.Text.title = "Level";

  kdTree->GenerateRepresentation(sp.Range.value, polydata);

  auto sliderWidget = Make2DSliderWidget(sp, iren);

  vtkNew<vtkSliderCallback> callback;
  callback->kdTree = kdTree;
  callback->polydata = polydata;
  callback->Execute(sliderWidget, 0, 0);

  sliderWidget->AddObserver(vtkCommand::InteractionEvent, callback);

  renWin->Render();
  iren->Initialize();
  iren->Start();

  return EXIT_SUCCESS;
}

namespace {

vtkNew<vtkPolyData> ReadPolyData(fs::path const& path)
{

  vtkNew<vtkPolyData> polyData;

  if (path.empty())
  {
    // Default to a sphere if the path is empty.
    vtkNew<vtkSphereSource> source;
    source->SetPhiResolution(50);
    source->SetThetaResolution(50);
    source->Update();
    polyData->DeepCopy(source->GetOutput());
    return polyData;
  }

  std::string extension = path.extension().generic_string();
  std::transform(extension.begin(), extension.end(), extension.begin(),
                 [](char c) { return std::tolower(c); });

  if (extension == ".ply")
  {
    vtkNew<vtkPLYReader> reader;
    reader->SetFileName(path.generic_string().c_str());
    reader->Update();
    polyData->DeepCopy(reader->GetOutput());
  }
  else if (extension == ".vtp")
  {
    vtkNew<vtkXMLPolyDataReader> reader;
    reader->SetFileName(path.generic_string().c_str());
    reader->Update();
    polyData->DeepCopy(reader->GetOutput());
  }
  else if (extension == ".obj")
  {
    vtkNew<vtkOBJReader> reader;
    reader->SetFileName(path.generic_string().c_str());
    reader->Update();
    polyData->DeepCopy(reader->GetOutput());
  }
  else if (extension == ".stl")
  {
    vtkNew<vtkSTLReader> reader;
    reader->SetFileName(path.generic_string().c_str());
    reader->Update();
    polyData->DeepCopy(reader->GetOutput());
  }
  else if (extension == ".vtk")
  {
    vtkNew<vtkPolyDataReader> reader;
    reader->SetFileName(path.generic_string().c_str());
    reader->Update();
    polyData->DeepCopy(reader->GetOutput());
  }
  else if (extension == ".g")
  {
    vtkNew<vtkBYUReader> reader;
    reader->SetGeometryFileName(path.generic_string().c_str());
    reader->Update();
    polyData->DeepCopy(reader->GetOutput());
  }
  else
  {
    std::cerr << "Warning: " << path
              << "unknown extension, using a sphere instead." << std::endl;
    vtkNew<vtkSphereSource> source;
    source->SetPhiResolution(50);
    source->SetThetaResolution(50);
    source->Update();
    polyData->DeepCopy(source->GetOutput());
  }
  return polyData;
}

Slider2DProperties MakeSlider2DProperties()
{
  auto sp = Slider2DProperties();

  // Set color properties:
  // Change the color of the knob that slides.
  sp.Colors.sliderColor = "Green";
  // Change the color of the text indicating what the slider controls.
  sp.Colors.titleColor = "AliceBlue";
  // Change the color of the text displaying the value.
  sp.Colors.labelColor = "AliceBlue";
  // Change the color of the knob when the mouse is held on it.
  sp.Colors.selectedColor = "DeepPink";
  // Change the color of the bar.
  sp.Colors.barColor = "MistyRose";
  // Change the color of the ends of the bar.
  sp.Colors.barEndsColor = "Yellow";
  sp.Dimensions.sliderLength = 0.05;
  sp.Dimensions.sliderWidth = 0.025;
  sp.Dimensions.endCapLength = 0.02;
  sp.Dimensions.titleHeight = 0.045;
  sp.Dimensions.labelHeight = 0.035;
  sp.Position.point1 = std::array<double, 2>{0.3, 0.1};
  sp.Position.point2 = std::array<double, 2>{0.7, 0.1};

  return sp;
}

vtkNew<vtkSliderWidget> Make2DSliderWidget(Slider2DProperties const& properties,
                                           vtkRenderWindowInteractor* iren)
{
  vtkNew<vtkNamedColors> colors;

  vtkNew<vtkSliderRepresentation2D> sliderRep;

  sliderRep->SetMinimumValue(properties.Range.minimumValue);
  sliderRep->SetMaximumValue(properties.Range.maximumValue);
  sliderRep->SetValue(properties.Range.value);
  sliderRep->SetTitleText(properties.Text.title.c_str());
  sliderRep->SetTubeWidth(properties.Dimensions.tubeWidth);
  sliderRep->SetSliderLength(properties.Dimensions.sliderLength);
  sliderRep->SetSliderWidth(properties.Dimensions.sliderWidth);
  sliderRep->SetEndCapLength(properties.Dimensions.endCapLength);
  sliderRep->SetEndCapWidth(properties.Dimensions.endCapWidth);
  sliderRep->SetTitleHeight(properties.Dimensions.titleHeight);
  sliderRep->SetLabelHeight(properties.Dimensions.labelHeight);

  // Set the color properties.
  sliderRep->GetTitleProperty()->SetColor(
      colors->GetColor3d(properties.Colors.titleColor).GetData());
  sliderRep->GetLabelProperty()->SetColor(
      colors->GetColor3d(properties.Colors.labelColor).GetData());
  sliderRep->GetTubeProperty()->SetColor(
      colors->GetColor3d(properties.Colors.barColor).GetData());
  sliderRep->GetCapProperty()->SetColor(
      colors->GetColor3d(properties.Colors.barEndsColor).GetData());
  sliderRep->GetSliderProperty()->SetColor(
      colors->GetColor3d(properties.Colors.sliderColor).GetData());
  sliderRep->GetSelectedProperty()->SetColor(
      colors->GetColor3d(properties.Colors.selectedColor).GetData());

  // Set the position.
  sliderRep->GetPoint1Coordinate()->SetCoordinateSystem(
      properties.Position.coordinateSystem);
  sliderRep->GetPoint1Coordinate()->SetValue(properties.Position.point1.data());
  sliderRep->GetPoint2Coordinate()->SetCoordinateSystem(
      properties.Position.coordinateSystem);
  sliderRep->GetPoint2Coordinate()->SetValue(properties.Position.point2.data());

  std::string titleFontFamily = properties.Text.titleFontFamily;
  if (titleFontFamily == "Courier")
  {
    sliderRep->GetLabelProperty()->SetFontFamilyToCourier();
  }
  else if (titleFontFamily == "Times")
  {
    sliderRep->GetLabelProperty()->SetFontFamilyToTimes();
  }
  else
  {
    sliderRep->GetLabelProperty()->SetFontFamilyToArial();
  }
  sliderRep->GetTitleProperty()->SetBold(properties.Text.titleBold);
  sliderRep->GetTitleProperty()->SetItalic(properties.Text.titleItalic);
  sliderRep->GetTitleProperty()->SetShadow(properties.Text.titleShadow);
  std::string labelFontFamily = properties.Text.labelFontFamily;
  if (labelFontFamily == "Courier")
  {
    sliderRep->GetLabelProperty()->SetFontFamilyToCourier();
  }
  else if (labelFontFamily == "Times")
  {
    sliderRep->GetLabelProperty()->SetFontFamilyToTimes();
  }
  else
  {
    sliderRep->GetLabelProperty()->SetFontFamilyToArial();
  }
  sliderRep->GetLabelProperty()->SetBold(properties.Text.labelBold);
  sliderRep->GetLabelProperty()->SetItalic(properties.Text.labelItalic);
  sliderRep->GetLabelProperty()->SetShadow(properties.Text.labelShadow);

  vtkNew<vtkSliderWidget> widget;
  widget->SetInteractor(iren);
  widget->SetRepresentation(sliderRep);
  widget->EnabledOn();
  widget->SetAnimationModeToAnimate();

  return widget;
}
} // namespace

CMakeLists.txt

cmake_minimum_required(VERSION 3.12 FATAL_ERROR)

project(VisualizeKDTree)

find_package(VTK COMPONENTS 
  CommonColor
  CommonCore
  CommonDataModel
  FiltersSources
  IOGeometry
  IOLegacy
  IOPLY
  IOXML
  InteractionStyle
  InteractionWidgets
  RenderingContextOpenGL2
  RenderingCore
  RenderingFreeType
  RenderingGL2PSOpenGL2
  RenderingOpenGL2
)

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

Download and Build VisualizeKDTree

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

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

./VisualizeKDTree

WINDOWS USERS

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