Skip to content

ReadAllPolyDataTypesDemo

Repository source: ReadAllPolyDataTypesDemo


Description

This example displays a model from each of the supported vtkPolyData readers.

Other languages

See (PythonicAPI)

Question

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

Code

ReadAllPolyDataTypesDemo.cxx

#include <vtkActor.h>
#include <vtkActor2D.h>
#include <vtkBYUReader.h>
#include <vtkCamera.h>
#include <vtkCellArray.h>
#include <vtkCoordinate.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkOBJReader.h>
#include <vtkPLYReader.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolyDataMapper2D.h>
#include <vtkPolyDataReader.h>
#include <vtkPolyLine.h>
#include <vtkProperty.h>
#include <vtkProperty2D.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSTLReader.h>
#include <vtkSmartPointer.h>
#include <vtkSphereSource.h>
#include <vtkTextActor.h>
#include <vtkTextMapper.h>
#include <vtkTextProperty.h>
#include <vtkTextRepresentation.h>
#include <vtkTextWidget.h>
#include <vtkXMLPolyDataReader.h>
#include <vtk_cli11.h>

#include <algorithm>
#include <filesystem>
#include <string>

namespace fs = std::filesystem;

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

/** Specify the rules for drawing the borders around a viewport.
 *
 * Here the borders for the viewports are defined in the order
 *  [top, left, bottom, right].
 *
 * Names for adjacent sides reflect anticlockwise ordering.
 */
static constexpr struct ViewportBorderSpecifier
{
  std::array<bool, 4> t{true, false, false, false};
  std::array<bool, 4> l{false, true, false, false};
  std::array<bool, 4> b{false, false, true, false};
  std::array<bool, 4> r{false, false, false, true};
  std::array<bool, 4> lb{false, true, true, false};
  std::array<bool, 4> lbr{false, true, true, true};
  std::array<bool, 4> tlb{true, true, true, false};
  std::array<bool, 4> tlbr{true, true, true, true};
  std::array<bool, 4> rtl{true, true, false, true};
  std::array<bool, 4> tl{true, true, false, false};
} viewportBorderSpecifier;

/** Draw a border around a viewport.
 *
 * @param renderer: The renderer corresponding to the viewport.
 * @param sides: An array of boolean corresponding to [top, left, bottom, right]
 * @param border_color: The color of the border.
 * @param border_width: The width of the border.
 * @return The border actor.
 */
vtkNew<vtkActor2D> DrawViewportBorder(std::array<bool, 4> const& sides,
                                      std::string const& border_color,
                                      unsigned int const& border_width);

typedef std::map<std::string, std::array<double, 2>> TTextPosition;
typedef std::map<std::string, TTextPosition> TTextPositions;

/** Get viewport positioning information for a vector of names.
 *
 * Note: You must include vtkSystemIncludes.h to get these defines:
 *  VTK_TEXT_LEFT 0, VTK_TEXT_CENTERED 1, VTK_TEXT_RIGHT 2,
 *  VTK_TEXT_BOTTOM 0, VTK_TEXT_TOP 2
 *
 *  @param names - The vector of names.
 *  @param justification - Horizontal justification of the text.
 *  @param vertical_justification - Vertical justification of the text.
 *  @param width - Width of the bounding_box of the text in screen coordinates.
 *  @param height - Height of the bounding_box of the text in screen
 *                  coordinates.
 *  @return A map of positioning information for exch name in names.
 */
TTextPositions
GetTextPositions(std::vector<std::string> const& names,
                 int const justification = VTK_TEXT_LEFT,
                 int const vertical_justification = VTK_TEXT_BOTTOM,
                 double const width = 0.95, double const height = 0.1);

} // namespace

int main(int argc, char* argv[])
{
  CLI::App app{
      "Display a model from each of the supported vtkPolyData readers."};

  std::vector<std::string> fileNames;
  app.add_option("fileName", fileNames, "List of files")
      ->check(CLI::ExistingFile);

  CLI11_PARSE(app, argc, argv);

  if (fileNames.empty())
  {
    std::cout << "No filenames have been specified." << std::endl;
    return EXIT_FAILURE;
  }

  std::vector<fs::path> fpNames;
  for (const auto& name : fileNames)
  {
    fs::path fp{name};
    fpNames.push_back(fp);
  }

  // Visualize
  vtkNew<vtkNamedColors> colors;

  // Setup viewports for the renderers
  unsigned int rendererSize = 400;
  unsigned int xGridDimensions = 3;
  unsigned int yGridDimensions =
      static_cast<unsigned int>(fpNames.size()) / xGridDimensions;
  if (fileNames.size() > xGridDimensions * yGridDimensions)
  {
    yGridDimensions++;
  }

  auto lastCol{false};
  auto lastRow{false};
  auto blank = fileNames.size();

  // Specify what borders will be drawn around each viewport.
  struct VP
  {
    std::string name{""};
    // Viewport dimensions [xmin, ymin, xmax, ymax].
    std::array<double, 4> viewport{0.0, 0.0, 0.0, 0.0};
    // What borders will be drawn around the viewport.
    std::array<bool, 4> border{false, false, false, false};
  };
  std::map<unsigned int, VP> viewports;

  // Titles for each viewport.
  std::vector<std::string> titles;

  for (unsigned int row = 0; row < yGridDimensions; ++row)
  {
    if (row == yGridDimensions - 1)
    {
      lastRow = true;
    }
    for (unsigned int col = 0; col < xGridDimensions; ++col)
    {
      if (col == xGridDimensions - 1)
      {
        lastCol = true;
      }
      auto index = row * xGridDimensions + col;

      // (xmin, ymin, xmax, ymax)
      std::array<double, 4> viewport{
          static_cast<double>(col) / xGridDimensions,
          static_cast<double>(yGridDimensions - (row + 1)) / yGridDimensions,
          static_cast<double>(col + 1) / xGridDimensions,
          static_cast<double>(yGridDimensions - row) / yGridDimensions};

      // Decide what borders will be drawn around the viewport.
      std::array<bool, 4> border;
      if (lastRow && lastCol)
      {
        border = viewportBorderSpecifier.tlbr;
        lastRow = false;
        lastCol = false;
      }
      else if (lastCol)
      {
        border = viewportBorderSpecifier.rtl;
        lastCol = false;
      }
      else if (lastRow)
      {
        border = viewportBorderSpecifier.tlb;
      }
      else
      {
        border = viewportBorderSpecifier.tl;
      }
      if (index < blank)
      {
        auto name = fpNames[index].filename().generic_string();
        titles.push_back(name);
        viewports[index] = {name, viewport, border};
      }
      else
      {
        viewports[index] = {"", viewport, border};
      }
    }
  }

  // Create the render window and interactor.
  vtkNew<vtkRenderWindow> renWin;
  renWin->SetWindowName("ReadAllPolyDataTypesDemo");
  vtkNew<vtkRenderWindowInteractor> iRen;
  iRen->SetRenderWindow(renWin);
  renWin->SetSize(rendererSize * xGridDimensions,
                  rendererSize * yGridDimensions);

  // Create a common text property for all.
  vtkNew<vtkTextProperty> textProperty;
  textProperty->SetColor(colors->GetColor3d("LightGoldenrodYellow").GetData());
  textProperty->BoldOn();
  textProperty->ItalicOn();
  textProperty->ShadowOn();
  textProperty->SetFontFamilyAsString("Courier");
  textProperty->SetFontSize(16);
  textProperty->SetJustificationToCentered();

  // Position text according to its length and left bottom in the viewport.
  auto textPositions =
      GetTextPositions(titles, VTK_TEXT_CENTERED, VTK_TEXT_BOTTOM, 0.5, 0.1);

  std::vector<vtkSmartPointer<vtkTextWidget>> textWidgets;

  // Create and link the mappers actors and renderers together.
  for (unsigned int index = 0; index < viewports.size(); ++index)
  {

    auto name = viewports[index].name;
    auto viewport = viewports[index].viewport;
    auto border = viewports[index].border;

    vtkNew<vtkRenderer> renderer;
    renderer->SetViewport(viewport.data());
    renderer->SetBackground(colors->GetColor3d("SlateGray").GetData());
    auto borderActor = DrawViewportBorder(border, "Yellow", 4);
    renderer->AddViewProp(borderActor);
    if (name.empty())
    {
      // Add a renderer even if the border is the only actor.
      // This makes the render window backgrounds all the same color.
      renWin->AddRenderer(renderer);
      continue;
    }

    auto polyData = ReadPolyData(fileNames[index]);
    vtkNew<vtkPolyDataMapper> mapper;
    mapper->SetInputData(polyData);
    vtkNew<vtkActor> actor;
    actor->SetMapper(mapper);
    actor->GetProperty()->SetDiffuseColor(
        colors->GetColor3d("LightSalmon").GetData());
    actor->GetProperty()->SetSpecular(0.6);
    actor->GetProperty()->SetSpecularPower(30);
    renderer->AddActor(actor);

    // Create the text actor and representation.
    vtkNew<vtkTextActor> textActor;
    textActor->SetInput(name.c_str());
    textActor->SetTextScaleModeToNone();
    textActor->SetTextProperty(textProperty);

    // Create the text representation. Used for positioning the text actor.
    vtkNew<vtkTextRepresentation> textRepresentation;
    textRepresentation->EnforceNormalizedViewportBoundsOff();
    textRepresentation->GetPositionCoordinate()->SetValue(
        textPositions[name]["p"].data());
    textRepresentation->GetPosition2Coordinate()->SetValue(
        textPositions[name]["p2"].data());

    // Create the text widget, setting the default renderer and interactor.
    vtkNew<vtkTextWidget> textWidget;
    textWidget->SetRepresentation(textRepresentation);
    textWidget->SetDefaultRenderer(renderer);
    textWidget->SetInteractor(iRen);
    textWidget->SetTextActor(textActor);
    textWidget->SelectableOff();
    textWidget->ResizableOn();
    textWidgets.push_back(textWidget);

    renWin->AddRenderer(renderer);

    textWidgets[index]->On();
  }

  for (auto& tw : textWidgets)
  {
    tw->On();
  }

  renWin->Render();
  iRen->Start();

  return EXIT_SUCCESS;
}

namespace {

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

  vtkNew<vtkPolyData> 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;
}

vtkNew<vtkActor2D> DrawViewportBorder(std::array<bool, 4> const& sides,
                                      std::string const& border_color,
                                      unsigned int const& border_width)
{
  vtkNew<vtkNamedColors> colors;

  // Points start at upper right and proceed anti-clockwise.
  vtkNew<vtkPoints> points;
  points->InsertPoint(0, 1, 1, 0);
  points->InsertPoint(1, 0, 1, 0);
  points->InsertPoint(2, 0, 0, 0);
  points->InsertPoint(3, 1, 0, 0);

  vtkNew<vtkCellArray> cells;

  if (sides[0])
  {
    // Top
    vtkNew<vtkPolyLine> top;
    top->GetPointIds()->SetNumberOfIds(2);
    top->GetPointIds()->SetId(0, 0);
    top->GetPointIds()->SetId(1, 1);
    cells->InsertNextCell(top);
  }
  if (sides[1])
  {
    // Left
    vtkNew<vtkPolyLine> left;
    left->GetPointIds()->SetNumberOfIds(2);
    left->GetPointIds()->SetId(0, 1);
    left->GetPointIds()->SetId(1, 2);
    cells->InsertNextCell(left);
  }
  if (sides[2])
  {
    // Bottom
    vtkNew<vtkPolyLine> bottom;
    bottom->GetPointIds()->SetNumberOfIds(2);
    bottom->GetPointIds()->SetId(0, 2);
    bottom->GetPointIds()->SetId(1, 3);
    cells->InsertNextCell(bottom);
  }
  if (sides[3])
  {
    // Right
    vtkNew<vtkPolyLine> right;
    right->GetPointIds()->SetNumberOfIds(2);
    right->GetPointIds()->SetId(0, 3);
    right->GetPointIds()->SetId(1, 0);
    cells->InsertNextCell(right);
  }

  // Now make the polydata and display it.
  vtkNew<vtkPolyData> poly;
  poly->SetPoints(points);
  poly->SetLines(cells);

  // Use normalized viewport coordinates since
  // they are independent of window size.
  vtkNew<vtkCoordinate> coordinate;
  coordinate->SetCoordinateSystemToNormalizedViewport();

  vtkNew<vtkPolyDataMapper2D> mapper;
  mapper->SetInputData(poly);
  mapper->SetTransformCoordinate(coordinate);

  vtkNew<vtkActor2D> actor;
  actor->SetMapper(mapper);
  actor->GetProperty()->SetColor(colors->GetColor3d(border_color).GetData());
  // Line width should be at least 2 to be visible at extremes.
  actor->GetProperty()->SetLineWidth(border_width);

  return actor;
}

TTextPositions GetTextPositions(std::vector<std::string> const& names,
                                int const justification,
                                int const vertical_justification,
                                double const width, double const height)
{
  // The gap between the left or right edge of the screen and the text.
  auto dx = 0.02;
  auto w = abs(width);
  if (w > 0.96)
  {
    w = 0.96;
  }

  auto y0 = 0.01;
  auto h = abs(height);
  if (h > 0.9)
  {
    h = 0.9;
  }
  auto dy = h;
  if (vertical_justification == VTK_TEXT_TOP)
  {
    y0 = 1.0 - (dy + y0);
  }
  if (vertical_justification == VTK_TEXT_CENTERED)
  {
    y0 = 0.5 - (dy / 2.0 + y0);
  }

  auto minmaxIt =
      std::minmax_element(names.begin(), names.end(),
                          [](const std::string& a, const std::string& b) {
                            return a.length() < b.length();
                          });

  // auto nameLenMin = minmaxIt.first->size();
  auto nameLenMax = minmaxIt.second->size();

  TTextPositions textPositions;
  for (const auto& k : names)
  {
    auto sz = k.size();
    auto delta_sz = w * sz / nameLenMax;
    if (delta_sz > w)
    {
      delta_sz = w;
    }

    double x0 = 0;
    if (justification == VTK_TEXT_CENTERED)
    {
      x0 = 0.5 - delta_sz / 2.0;
    }
    else if (justification == VTK_TEXT_RIGHT)
    {
      x0 = 1.0 - dx - delta_sz;
    }
    else
    {
      // Default is left justification.
      x0 = dx;
    }
    textPositions[k] = {{"p", {x0, y0}}, {"p2", {delta_sz, dy}}};
    // For testing.
    // std::cout << k << std::endl;
    // std::cout << "  p: " << textPositions[k]["p"][0] << ", "
    //           << textPositions[k]["p"][1] << std::endl;
    // std::cout << " p2: " << textPositions[k]["p2"][0] << ", "
    //           << textPositions[k]["p2"][1] << std::endl;
  }
  return textPositions;
}

} // namespace

CMakeLists.txt

cmake_minimum_required(VERSION 3.12 FATAL_ERROR)

project(ReadAllPolyDataTypesDemo)

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

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

Download and Build ReadAllPolyDataTypesDemo

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

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

./ReadAllPolyDataTypesDemo

WINDOWS USERS

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