Skip to content

InterpolateCamera

Repository source: InterpolateCamera


Description

This example uses vtkCameraInterpolator to generate a smooth interpolation between camera views. The key points for the camera positions are generated from the vtkPolyData's bounding box. The camera focal points are at the center of the polydata.

The key points are computed from the corners of the bounding box. They are pushed out along a vector from the center to the corner point. The amount of pushing is a random multiplier of the range of the data.

Other languages

See (PythonicAPI)

Question

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

Code

InterpolateCamera.cxx

#include <vtkActor.h>
#include <vtkCamera.h>
#include <vtkCameraInterpolator.h>
#include <vtkMinimalStandardRandomSequence.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkPoints.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSmartPointer.h>

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

#include <vtksys/SystemTools.hxx>

#include <array>
#include <chrono>
#include <iterator>
// #include <random>
#include <thread>
#include <vector>

namespace {
vtkSmartPointer<vtkPolyData> ReadPolyData(const char* fileName);

void ComputeKeyPoints(vtkPolyData* polyData, std::array<double, 3>& center,
                      std::vector<std::array<double, 3>>& keyPoints);

template <class T, std::size_t N>
ostream& operator<<(ostream& o, const std::array<T, N>& arr)
{
  copy(arr.cbegin(), arr.cend(), std::ostream_iterator<T>(o, ", "));
  return o;
}

template <class T, std::size_t N>
ostream& operator<<(ostream& o, const std::vector<T>& vec)
{
  copy(vec.cbegin(), vec.cend(), std::ostream_iterator<T>(o, ", "));
  return o;
}

} // namespace

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

  vtkNew<vtkNamedColors> colors;

  // E.g. spider.ply
  vtkSmartPointer<vtkPolyData> polyData = ReadPolyData(argc > 1 ? argv[1] : "");

  // Setup camera views for interpolation
  vtkNew<vtkCameraInterpolator> interpolator;
  interpolator->SetInterpolationTypeToSpline();

  std::array<double, 3> center;
  std::vector<std::array<double, 3>> keyPoints;
  ComputeKeyPoints(polyData, center, keyPoints);

  for (size_t i = 0; i < keyPoints.size() + 1; ++i)
  {
    // auto j = i;
    vtkNew<vtkCamera> cam;
    cam->SetFocalPoint(center.data());
    if (i < keyPoints.size())
    {
      cam->SetPosition(keyPoints[i].data());
    }
    else
    {
      cam->SetPosition(keyPoints[0].data());
    }
    cam->SetViewUp(0.0, 0.0, 1.0);
    interpolator->AddCamera((double)i, cam);
  }

  // Visualize
  vtkNew<vtkPolyDataMapper> mapper;
  mapper->SetInputData(polyData);
  mapper->ScalarVisibilityOff();

  vtkNew<vtkProperty> backProp;
  backProp->SetDiffuseColor(colors->GetColor3d("Banana").GetData());
  backProp->SetDiffuse(.76);
  backProp->SetSpecular(.4);
  backProp->SetSpecularPower(30);
  ;

  vtkNew<vtkActor> actor;
  actor->SetMapper(mapper);
  actor->SetBackfaceProperty(backProp);
  actor->GetProperty()->SetDiffuseColor(
      colors->GetColor3d("Crimson").GetData());
  actor->GetProperty()->SetSpecular(.6);
  actor->GetProperty()->SetSpecularPower(30);

  vtkNew<vtkRenderer> renderer;
  vtkNew<vtkRenderWindow> renderWindow;
  renderWindow->AddRenderer(renderer);
  renderWindow->SetSize(640, 480);
  renderWindow->SetWindowName("InterpolateCamera");

  vtkNew<vtkRenderWindowInteractor> renderWindowInteractor;
  renderWindowInteractor->SetRenderWindow(renderWindow);

  renderer->AddActor(actor);
  renderer->SetBackground(colors->GetColor3d("Silver").GetData());

  vtkNew<vtkCamera> camera;
  renderer->SetActiveCamera(camera);

  auto numSteps = 600;
  auto minT = interpolator->GetMinimumT();
  auto maxT = interpolator->GetMaximumT();
  for (auto i = 0; i < numSteps; ++i)
  {
    double t = (double)i * (maxT - minT) / (double)(numSteps - 1);
    interpolator->InterpolateCamera(t, camera);
    renderer->ResetCameraClippingRange();
    renderWindow->Render();
    std::this_thread::sleep_for(std::chrono::milliseconds(50));
  }

  renderWindowInteractor->Start();

  return EXIT_SUCCESS;
}

namespace {
vtkSmartPointer<vtkPolyData> ReadPolyData(const char* fileName)
{
  vtkSmartPointer<vtkPolyData> polyData;
  std::string extension =
      vtksys::SystemTools::GetFilenameLastExtension(std::string(fileName));
  if (extension == ".ply")
  {
    vtkNew<vtkPLYReader> reader;
    reader->SetFileName(fileName);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else if (extension == ".vtp")
  {
    vtkNew<vtkXMLPolyDataReader> reader;
    reader->SetFileName(fileName);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else if (extension == ".obj")
  {
    vtkNew<vtkOBJReader> reader;
    reader->SetFileName(fileName);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else if (extension == ".stl")
  {
    vtkNew<vtkSTLReader> reader;
    reader->SetFileName(fileName);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else if (extension == ".vtk")
  {
    vtkNew<vtkPolyDataReader> reader;
    reader->SetFileName(fileName);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else if (extension == ".g")
  {
    vtkNew<vtkBYUReader> reader;
    reader->SetGeometryFileName(fileName);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else
  {
    vtkNew<vtkSphereSource> source;
    source->Update();
    polyData = source->GetOutput();
  }
  return polyData;
}

void ComputeKeyPoints(vtkPolyData* polyData, std::array<double, 3>& center,
                      std::vector<std::array<double, 3>>& keyPoints)
{
  // std::mt19937 mt(4355412); // Standard mersenne_twister_engine
  // std::uniform_real_distribution<double> dis(1.0, 3.0);

  vtkNew<vtkMinimalStandardRandomSequence> randomSequence;
  randomSequence->SetSeed(4355412);

  // Get Bounding Box
  std::array<double, 6> bounds;
  polyData->GetBounds(bounds.data());

  double range;
  range = std::max(std::max(bounds[1] - bounds[0], bounds[3] - bounds[2]),
                   bounds[5] - bounds[4]);

  std::vector<std::array<double, 3>> points(8);
  std::array<double, 3> point;
  point = {{bounds[0], bounds[2], bounds[4]}};
  points[0] = point;

  point = {{bounds[1], bounds[2], bounds[4]}};
  points[1] = point;

  point = {{bounds[1], bounds[2], bounds[5]}};
  points[2] = point;

  point = {{bounds[0], bounds[2], bounds[5]}};
  points[3] = point;

  point = {{bounds[0], bounds[3], bounds[4]}};
  points[4] = point;

  point = {{bounds[1], bounds[3], bounds[4]}};
  points[5] = point;

  point = {{bounds[1], bounds[3], bounds[5]}};
  points[6] = point;

  point = {{bounds[0], bounds[3], bounds[5]}};
  points[7] = point;

  polyData->GetCenter(center.data());

  for (size_t i = 0; i < points.size(); ++i)
  {
    std::array<double, 3> direction;
    for (auto j = 0; j < 3; ++j)
    {
      direction[j] = points[i][j] - center[j];
    }
    vtkMath::Normalize(direction.data());
    // double factor = dis(mt);
    double factor = randomSequence->GetRangeValue(1.0, 3.0);
    randomSequence->Next();
    keyPoints.resize(8);
    for (auto j = 0; j < 3; ++j)
    {
      keyPoints[i][j] = points[i][j] + direction[j] * range * factor;
    }
  }
}
} // namespace

CMakeLists.txt

cmake_minimum_required(VERSION 3.12 FATAL_ERROR)

project(InterpolateCamera)

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

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

Download and Build InterpolateCamera

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

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

./InterpolateCamera

WINDOWS USERS

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