Skip to content

PlatonicSolids

Repository source: PlatonicSolids


Description

Display all five Platonic solids in a grid.

Platonic solids are regular, convex polyhedrons. They are constructed by congruent (identical in shape and size) regular (all angles equal and all sides equal) polygonal faces with the same number of faces meeting at each vertex.

Five solids satisfy the above criteria:

Figure Tetrahedron Cube Octahedron Icosahedron Dodecahedron
Vertices 4 8 6 (2 × 3) 12 (4 × 3) 20 (8 + 4 × 3)
Edges 6 12 12 30 30
Faces 4 6 8 20 12

The relationship between vertices, edges and faces is given by Euler's formula:

V - E + F = 2

Other languages

See (Python), (PythonicAPI)

Question

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

Code

PlatonicSolids.cxx

#include <vtkActor2D.h>
#include <vtkCamera.h>
#include <vtkCellArray.h>
#include <vtkCoordinate.h>
#include <vtkLookupTable.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkPlatonicSolidSource.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolyDataMapper2D.h>
#include <vtkPolyLine.h>
#include <vtkProperty2D.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSmartPointer.h>
#include <vtkTextActor.h>
#include <vtkTextMapper.h>
#include <vtkTextProperty.h>
#include <vtkTextRepresentation.h>
#include <vtkTextWidget.h>

#include <array>
#include <string>
#include <vector>

namespace {
/** 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.96, double const height = 0.1);

/** Specify the name of the platonic solid and its initial orientation.
 *
 */
struct NameOrientation
{
  std::string name{""};
  // [azimuth, elevation, zoom]
  std::array<double, 3> orientation{0.0, 0.0, 0.0};
};
// An ordered map of the name and orientation of each platonic solid.
typedef std::map<unsigned int, NameOrientation> TNameOrientations;

/** Get the platonic solid names and initial orientations.
 *
 * @return The solids and their initial orientations.
 */
TNameOrientations GetNameOrientation();

/** Get a specialised lookup table for the platonic solids.
 *
 * Since each face of a vtkPlatonicSolidSource has a different
 * cell scalar, we create a lookup table with a different colour
 * for each face.
 * The colors have been carefully chosen so that adjacent cells
 * are colored distinctly.
 *
 * @return The lookup table.
 */
vtkNew<vtkLookupTable> GetPlatonicLUT();

} // namespace

int main(int, char*[])
{
  vtkNew<vtkNamedColors> colors;

  // Platonic solids and orientation for display.
  auto nameOrientation = GetNameOrientation();
  auto lut = GetPlatonicLUT();
  std::vector<vtkSmartPointer<vtkPlatonicSolidSource>> platonicSolids;

  // Set up the viewports
  unsigned int xGridDimensions = 3;
  unsigned int yGridDimensions = 2;
  unsigned int rendererSize = 300;

  auto lastCol{false};
  auto lastRow{false};
  auto blank = nameOrientation.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;

  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)
      {
        viewports[index] = {nameOrientation[index].name, viewport, border};
      }
      else
      {
        viewports[index] = {"", viewport, border};
      }
    }
  }

  // Create the render window and interactor.
  vtkNew<vtkRenderWindow> renWin;
  renWin->SetWindowName("PlatonicSolids");
  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("AliceBlue").GetData());
  textProperty->BoldOn();
  textProperty->ShadowOn();
  textProperty->SetFontFamilyAsString("Courier");
  textProperty->SetFontSize(16);
  textProperty->SetJustificationToCentered();

  std::vector<std::string> titles;
  for (size_t i = 0; i < nameOrientation.size(); ++i)
  {
    if (!nameOrientation[static_cast<unsigned int>(i)].name.empty())
    {
      titles.push_back(nameOrientation[static_cast<unsigned int>(i)].name);
    }
  }
  // Position text according to its length and centered in the viewport.
  auto textPositions = GetTextPositions(titles, VTK_TEXT_CENTERED);

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

    vtkNew<vtkPlatonicSolidSource> platonicSolid;
    platonicSolid->SetSolidType(index);
    vtkNew<vtkPolyDataMapper> mapper;
    mapper->SetInputConnection(platonicSolid->GetOutputPort());
    mapper->SetLookupTable(lut);
    mapper->SetScalarRange(0, 19);
    vtkNew<vtkActor> actor;
    actor->SetMapper(mapper);
    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);

    // Orient the view.
    if (index < titles.size())
    {
      renderer->ResetCamera();
      renderer->GetActiveCamera()->Azimuth(
          nameOrientation[index].orientation[0]);
      renderer->GetActiveCamera()->Elevation(
          nameOrientation[index].orientation[1]);
      renderer->GetActiveCamera()->Zoom(nameOrientation[index].orientation[2]);
      renderer->ResetCameraClippingRange();

      renWin->AddRenderer(renderer);
    }
  }

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

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

  return EXIT_SUCCESS;
}

namespace {
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;
}

TNameOrientations GetNameOrientation()
{
  TNameOrientations res;
  res[0] = {"Tetrahedron", std::array<double, 3>{45.0, 30.0, 1.0}};
  res[1] = {"Cube", std::array<double, 3>{-60.0, 45.0, 0.8}};
  res[2] = {"Octahedron", {-15.0, 10.0, 1.0}};
  res[3] = {"Icosahedron", {4.5, 18.0, 1.0}};
  res[4] = {"Dodecahedron", {171.0, 22.0, 1.0}};

  return res;
}

vtkNew<vtkLookupTable> GetPlatonicLUT()
{
  vtkNew<vtkLookupTable> lut;
  lut->SetNumberOfTableValues(20);
  lut->SetTableRange(0.0, 19.0);
  lut->Build();
  lut->SetTableValue(0, 0.1, 0.1, 0.1);
  lut->SetTableValue(1, 0, 0, 1);
  lut->SetTableValue(2, 0, 1, 0);
  lut->SetTableValue(3, 0, 1, 1);
  lut->SetTableValue(4, 1, 0, 0);
  lut->SetTableValue(5, 1, 0, 1);
  lut->SetTableValue(6, 1, 1, 0);
  lut->SetTableValue(7, 0.9, 0.7, 0.9);
  lut->SetTableValue(8, 0.5, 0.5, 0.5);
  lut->SetTableValue(9, 0.0, 0.0, 0.7);
  lut->SetTableValue(10, 0.5, 0.7, 0.5);
  lut->SetTableValue(11, 0, 0.7, 0.7);
  lut->SetTableValue(12, 0.7, 0, 0);
  lut->SetTableValue(13, 0.7, 0, 0.7);
  lut->SetTableValue(14, 0.7, 0.7, 0);
  lut->SetTableValue(15, 0, 0, 0.4);
  lut->SetTableValue(16, 0, 0.4, 0);
  lut->SetTableValue(17, 0, 0.4, 0.4);
  lut->SetTableValue(18, 0.4, 0, 0);
  lut->SetTableValue(19, 0.4, 0, 0.4);
  return lut;
}

} // namespace

CMakeLists.txt

cmake_minimum_required(VERSION 3.12 FATAL_ERROR)

project(PlatonicSolids)

find_package(VTK COMPONENTS 
  CommonColor
  CommonCore
  FiltersSources
  InteractionStyle
  RenderingContextOpenGL2
  RenderingCore
  RenderingFreeType
  RenderingGL2PSOpenGL2
  RenderingOpenGL2
)

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

Download and Build PlatonicSolids

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

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

./PlatonicSolids

WINDOWS USERS

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