Skip to content

CameraOrientationWidget1

Repository source: CameraOrientationWidget1


Description

This example demonstrates the usage and versatility of the vtkCameraOrientationWidget, also, for comparison, a vtkOrientationMarkerWidget is provided. The ability to automatically change axes labels and colors depending upon the object being viewed is demonstrated. To do this, just load any one of the following files from the vtk-examples testing data.

"Human.vtp", "Torso.vtp", "cow.vtp", "cowHead.vtp", "horse.vtp", "Bunny.vtp"

These files are found in vtk-examples/src/Testing/Data.

The vtkCameraOrientationWidget has shafts and little spheres with text on them. The spheres alway follow the camera.

The widget representation's orientation is synchronized with the camera of the parent renderer.

To look down on any particular axis, simply click on a handle.

To rotate the camera and get a feel of the camera orientation, either move the mouse in the render window or click on a handle and move it around.

If no file name is entered, a cone is rendered.

Some history: - The vtkCameraOrientationWidget was introduced in the MR: !8156, 18 July, 2021. - Labelling of the vertices was introduced in the MR: !11665, 16 November, 2024. - Coloring of the vertices was introduced in the MR: !12489, 01 October, 2025

Other languages

See (PythonicAPI)

Question

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

Code

CameraOrientationWidget1.cxx

#include <vtkActor.h>
#include <vtkAxesActor.h>
#include <vtkBYUReader.h>
#include <vtkCameraOrientationRepresentation.h>
#include <vtkCameraOrientationWidget.h>
#include <vtkConeSource.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkOBJReader.h>
#include <vtkOrientationMarkerWidget.h>
#include <vtkPLYReader.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolyDataReader.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSTLReader.h>
#include <vtkSphereSource.h>
#include <vtkTransform.h>
#include <vtkTransformFilter.h>
#include <vtkXMLPolyDataReader.h>

#include <vtk_cli11.h>
#include <vtk_fmt.h>
// clang-format off
#include VTK_FMT(fmt/format.h)
// clang-format on

// #include <algorithm> // For transform()
// #include <array>
// #include <cctype> // For to_lower
// #include <cmath>
// #include <filesystem>
// #include <map>
// #include <string> // For find_last_of()

namespace fs = std::filesystem;

namespace {

typedef std::map<std::string, std::string> TAxisParams;
typedef std::map<std::string, TAxisParams> TAxesParams;

/**
 * Use a vtk file reader to get the polydata.
 *
 * @param path The filesystem path to the file.
 *
 * @return The polydata
 */
vtkSmartPointer<vtkPolyData> ReadPolyData(fs::path const& path);

/**
 * Make a camera orientation widget for a given renderer.
 *
 * @param ren The renderer.
 * @param axisLabels A map of labels for the axis.
 * @param axisColors A map of colors for the axis.
 *
 * @return The camera orientation widget.
 */
vtkSmartPointer<vtkCameraOrientationWidget>
MakeCameraOrientationWidget(vtkRenderer* ren, TAxisParams& axisLabels,
                            TAxisParams& axisColors);

/**
 * Make an axis actor.
 *
 * @param axisLabels A map of labels for the axis.
 * @param axisColors A map of colors for the axis.
 *
 * @return The axis actor.
 */
vtkSmartPointer<vtkAxesActor> MakeAxesActor(TAxisParams& axisLabels,
                                            TAxisParams& axisColors);

/**
 * Make an orientation marker for a given renderer.
 *
 * @param ren The renderer.
 * @param iren The interactor.
 * @param axisLabels A map of labels for the axis.
 * @param axisColors A map of colors for the axis.
 *
 * @return: The orientation marker widget.
 */
vtkSmartPointer<vtkOrientationMarkerWidget>
MakeOrientationMarkerWidget(vtkRenderer* renderer,
                            vtkRenderWindowInteractor* iren,
                            TAxisParams& axisLabels, TAxisParams& axisColors);

} // namespace

int main(int argc, char* argv[])
{

  vtkNew<vtkNamedColors> colors;
  colors->SetColor("ParaViewBlueGrayBkg",
                   std::array<unsigned char, 4>{84, 89, 109, 255}.data());
  colors->SetColor("ParaViewWarmGrayBkg",
                   std::array<unsigned char, 4>{98, 93, 90, 255}.data());

  CLI::App app{"Demonstrates the use of the Camera Orientation Widget."};

  // Define options
  std::string fileName{""};
  app.add_option("fileName", fileName,
                 "A optional path to a file that contains vtkPolyData e.g. "
                 "Human.vtp");

  CLI11_PARSE(app, argc, argv);

  auto path = fs::path(fileName);
  if (!path.empty())
  {
    if (!fs::is_regular_file(path))
    {
      std::cerr << fmt::format("Unable to find: {:s}", path.string())
                << std::endl;
      return EXIT_FAILURE;
    }
  }
  auto polyData = ReadPolyData(path);

  // Assign a category for the labels and colors.
  std::string category = "xyz";
  if (fs::is_regular_file(path))
  {
    auto isIn = [](std::string const& a, std::vector<std::string> const& v) {
      auto it = std::find(v.cbegin(), v.cend(), a);
      return it != v.cend();
    };
    auto pth = path.filename().string();
    typedef std::vector<std::string> Tvs;
    if (isIn(pth, Tvs{"Human.vtp", "Torso.vtp"}))
    {
      category = "lrsiap";
    }
    else if (isIn(pth, Tvs{"cow.vtp", "cowHead.vtp", "horse.vtp", "Bunny.vtp"}))
    {
      category = "apdvlr";
    }
  }

  // Define the axes labels and colors here.
  TAxesParams axesLabels = {
      // Labels are: Anterior, Posterior, Dorsal, Ventral, Left, Right
      {"apdvlr",
       {{"+X", "A"},
        {"-X", "P"},
        {"+Y", "D"},
        {"-Y", "V"},
        {"+Z", "L"},
        {"-Z", "R"}}},
      // Labels are: Left, Right, Superior, Inferior, Anterior, Posterior
      {"lrsiap",
       {{"+X", "L"},
        {"-X", "R"},
        {"+Y", "S"},
        {"-Y", "I"},
        {"+Z", "A"},
        {"-Z", "P"}}},
      // Default labels.
      {"xyz", {}},
  };
  TAxesParams axesColors = {
      {"apdvlr",
       {{"+X", "IndianRed"},
        {"-X", "FireBrick"},
        {"+Y", "LimeGreen"},
        {"-Y", "DarkGreen"},
        {"+Z", "Blue"},
        {"-Z", "SteelBlue"}}},
      {"lrsiap",
       {{"+X", "IndianRed"},
        {"-X", "FireBrick"},
        {"+Y", "LimeGreen"},
        {"-Y", "DarkGreen"},
        {"+Z", "Blue"},
        {"-Z", "SteelBlue"}}},
      // Default colors.
      {"xyz", {}},
  };

  vtkNew<vtkTransform> tran;
  tran->Identity();

  if (!path.empty())
  {
    auto pth = path.filename().string();
    if (pth == "Human.vtp")
    {
      tran->RotateY(180);
      tran->RotateX(-90);
    }
    if (pth == "Torso.vtp")
    {
      tran->RotateX(-90);
    }
    if (pth == "Bunny.vtp")
    {
      tran->RotateY(180);
    }
    if (pth == "horse.vtp")
    {
      tran->RotateY(270);
      tran->RotateX(-90);
    }
  }
  vtkNew<vtkTransformFilter> tf;
  tf->SetTransform(tran);
  tf->SetInputData(polyData);

  vtkNew<vtkPolyDataMapper> mapper;
  mapper->SetInputConnection(tf->GetOutputPort());

  vtkNew<vtkActor> actor;
  actor->GetProperty()->SetColor(colors->GetColor3d("Tan").GetData());
  actor->SetMapper(mapper);

  vtkNew<vtkRenderer> ren;
  vtkNew<vtkRenderWindow> renWin;
  vtkNew<vtkRenderWindowInteractor> iRen;
  renWin->AddRenderer(ren);
  renWin->SetSize(600, 600);
  auto appFn = fs::path((app.get_name())).stem().string();
  if (path.empty())
  {
    renWin->SetWindowName(appFn.c_str());
  }
  else
  {
    auto winName = fmt::format("{:s} {:s}", appFn, path.filename().string());
    renWin->SetWindowName(winName.c_str());
  }

  // Important: The interactor must be set prior
  //  to enabling the Camera Orientation Widget.
  iRen->SetRenderWindow(renWin);

  ren->AddActor(actor);
  ren->SetBackground(colors->GetColor3d("ParaViewBLueGrayBkg").GetData());

  auto cow = MakeCameraOrientationWidget(ren, axesLabels[category],
                                         axesColors[category]);
  auto omw = MakeOrientationMarkerWidget(ren, iRen, axesLabels[category],
                                         axesColors[category]);
  ren->ResetCamera();
  renWin->Render();
  iRen->Initialize();
  iRen->Start();

  return EXIT_SUCCESS;
}

namespace {
vtkSmartPointer<vtkPolyData> ReadPolyData(fs::path const& path)
{
  auto pth = path.string();
  auto fp = pth.c_str();
  auto extension = path.extension().string();
  vtkSmartPointer<vtkPolyData> polyData;
  if (extension == ".ply")
  {
    vtkNew<vtkPLYReader> reader;
    reader->SetFileName(fp);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else if (extension == ".vtp")
  {
    vtkNew<vtkXMLPolyDataReader> reader;
    reader->SetFileName(fp);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else if (extension == ".obj")
  {
    vtkNew<vtkOBJReader> reader;
    reader->SetFileName(fp);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else if (extension == ".stl")
  {
    vtkNew<vtkSTLReader> reader;
    reader->SetFileName(fp);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else if (extension == ".vtk")
  {
    vtkNew<vtkPolyDataReader> reader;
    reader->SetFileName(fp);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else if (extension == ".g")
  {
    vtkNew<vtkBYUReader> reader;
    reader->SetGeometryFileName(fp);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else
  {
    // Use a cone as a source with the golden ratio (φ) for the height.
    // Because we can!
    // If the short side is one then φ = 2 × sin(54°) or φ = 1/2 + √5 / 2
    vtkNew<vtkConeSource> source;
    source->SetCenter(0, 0, 0);
    source->SetRadius(1);
    source->SetHeight((1.0 + std::sqrt(5.0)) / 2.0);
    source->SetResolution(64);
    source->SetDirection(0, 1, 0);
    source->Update();
    polyData = source->GetOutput();
  }
  return polyData;
}

vtkSmartPointer<vtkCameraOrientationWidget>
MakeCameraOrientationWidget(vtkRenderer* ren, TAxisParams& axisLabels,
                            TAxisParams& axisColors)
{
  vtkNew<vtkNamedColors> colors;
  vtkNew<vtkCameraOrientationWidget> cow;
  cow->SetParentRenderer(ren);
  if (axisLabels.empty())
  {
    // Use the default vtkCameraOrientationWidget
    cow->EnabledOn();
    cow->On();

    return cow;
  }
  vtkNew<vtkCameraOrientationRepresentation> rep;

  rep->SetXPlusLabelText(axisLabels["+X"]);
  rep->SetXMinusLabelText(axisLabels["-X"]);
  rep->SetYPlusLabelText(axisLabels["+Y"]);
  rep->SetYMinusLabelText(axisLabels["-Y"]);
  rep->SetZPlusLabelText(axisLabels["+Z"]);
  rep->SetZMinusLabelText(axisLabels["-Z"]);

  rep->SetXAxisColor(colors->GetColor3d(axisColors["+X"]).GetData());
  rep->SetYAxisColor(colors->GetColor3d(axisColors["+Y"]).GetData());
  rep->SetZAxisColor(colors->GetColor3d(axisColors["+Z"]).GetData());

  cow->SetRepresentation(rep);

  cow->EnabledOn();
  cow->On();

  return cow;
}

vtkSmartPointer<vtkAxesActor> MakeAxesActor(TAxisParams& axisLabels,
                                            TAxisParams& axisColors)
{
  vtkNew<vtkNamedColors> colors;
  vtkNew<vtkAxesActor> axes;

  if (axisLabels.empty())
  {
    // Use the default vtkOrientationMarkerWidget
    return axes;
  }

  axes->SetXAxisLabelText(axisLabels["+X"].c_str());
  axes->SetYAxisLabelText(axisLabels["+Y"].c_str());
  axes->SetZAxisLabelText(axisLabels["+Z"].c_str());

  auto xShaftProp = axes->GetXAxisShaftProperty();
  xShaftProp->SetColor(colors->GetColor3d(axisColors["+X"]).GetData());
  auto xTipProp = axes->GetXAxisTipProperty();
  xTipProp->SetColor(colors->GetColor3d(axisColors["+X"]).GetData());

  auto yShaftProp = axes->GetYAxisShaftProperty();
  yShaftProp->SetColor(colors->GetColor3d(axisColors["+Y"]).GetData());
  auto yTipProp = axes->GetYAxisTipProperty();
  yTipProp->SetColor(colors->GetColor3d(axisColors["+Y"]).GetData());

  auto zShaftProp = axes->GetZAxisShaftProperty();
  zShaftProp->SetColor(colors->GetColor3d(axisColors["+Z"]).GetData());
  auto zTipProp = axes->GetZAxisTipProperty();
  zTipProp->SetColor(colors->GetColor3d(axisColors["+Z"]).GetData());
  return axes;
}

vtkSmartPointer<vtkOrientationMarkerWidget>
MakeOrientationMarkerWidget(vtkRenderer* ren, vtkRenderWindowInteractor* iren,
                            TAxisParams& axisLabels, TAxisParams& axisColors)
{
  vtkNew<vtkOrientationMarkerWidget> om;
  auto axesActor = MakeAxesActor(axisLabels, axisColors);
  om->SetOrientationMarker(axesActor);
  // Position lower left in the viewport.
  om->SetViewport(0, 0, 0.2, 0.2);
  om->SetInteractor(iren);
  om->SetDefaultRenderer(ren);
  om->EnabledOn();
  om->InteractiveOn();

  return om;
}

} // namespace

CMakeLists.txt

cmake_minimum_required(VERSION 3.12 FATAL_ERROR)

project(CameraOrientationWidget1)

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

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

Download and Build CameraOrientationWidget1

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

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

./CameraOrientationWidget1

WINDOWS USERS

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