/*=========================================================================

  Copyright (c) Kitware, Inc.
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/VolViewCopyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkObjectFactory.h"

#include "vtkCamera.h"
#include "vtkCellLabelAnnotation.h"
#include "vtkCoordinate.h"
#include "vtkMath.h"
#include "vtkRenderer.h"
#include "vtkSmartPointer.h"
#include "vtkStructuredGrid.h"
#include "vtkTextActor.h"
#include "vtkTextProperty.h"

#include <vtkstd/list>
#include <vtksys/ios/sstream>

vtkCxxRevisionMacro(vtkCellLabelAnnotation, "$Revision: 1.4 $");
vtkStandardNewMacro(vtkCellLabelAnnotation);

vtkCxxSetObjectMacro(vtkCellLabelAnnotation, Input, vtkStructuredGrid);
vtkCxxSetObjectMacro(vtkCellLabelAnnotation, DataActor, vtkActor);
vtkCxxSetObjectMacro(vtkCellLabelAnnotation, PreviousInput, vtkStructuredGrid);

struct vtkCellLabelAnnotationInternals
{
  typedef
  vtkstd::list<vtkSmartPointer<vtkTextActor> > CellLabelActorsType;
  CellLabelActorsType CellLabelActors;
};

#define VTK_MIN_DISTANCE_BETWEEN_LABELS 20
#define VTK_NUMBER_OF_PIXELS_FROM_EDGE 12

//----------------------------------------------------------------------------
vtkCellLabelAnnotation::vtkCellLabelAnnotation()
{
  this->Input = 0;
  this->DataActor = 0;
  this->PreviousInput = 0;
  this->ParallelScale = 0;
  this->ActorScale[0] = this->ActorScale[1] = this->ActorScale[2] = 0;
  this->ViewportSize[0] = this->ViewportSize[1] = 0;
  this->Extent[0] = this->Extent[1] = this->Extent[2] = this->Extent[3] =
    this->Extent[4] = this->Extent[5] = 0;
  this->Internal = new vtkCellLabelAnnotationInternals;
  this->MissingDimension = 0;
}

//----------------------------------------------------------------------------
vtkCellLabelAnnotation::~vtkCellLabelAnnotation()
{
  this->SetInput(0);
  this->SetDataActor(0);
  this->SetPreviousInput(0);
  delete this->Internal;
}

//----------------------------------------------------------------------------
int vtkCellLabelAnnotation::RenderOverlay(vtkViewport *viewport)
{
  int renderedSomething = 0;

  vtkCellLabelAnnotationInternals::CellLabelActorsType::iterator it =
    this->Internal->CellLabelActors.begin();
  vtkTextActor *actor;

  for (; it != this->Internal->CellLabelActors.end(); it++)
    {
    actor = *it;
    // actors were added to the renderer in ComputeLabelPositions
    renderedSomething += actor->RenderOverlay(viewport);
    }

  return renderedSomething;
}

//----------------------------------------------------------------------------
int vtkCellLabelAnnotation::RenderOpaqueGeometry(vtkViewport *viewport)
{
  if (!this->Input || !this->DataActor)
    {
    vtkErrorMacro("The Input and DataActor must be set to display cell labels.");
    return 0;
    }

  vtkRenderer *ren = vtkRenderer::SafeDownCast(viewport);
  if (!ren)
    {
    return 0;
    }
  vtkCamera *cam = ren->GetActiveCamera();
  double scale[3];
  this->DataActor->GetScale(scale);
  int *size = ren->GetSize();
  int ext[6];
  this->Input->GetWholeExtent(ext);

  if ((this->Input != this->PreviousInput) ||
      (cam->GetParallelScale() != this->ParallelScale) ||
      ( ! (scale[0] == this->ActorScale[0]) &&
        (scale[1] == this->ActorScale[1]) &&
        (scale[2] == this->ActorScale[2]) ) ||
      ( ! (size[0] != this->ViewportSize[0]) &&
        (size[1] != this->ViewportSize[1]) ) ||
      ( ! (ext[0] == this->Extent[0]) && (ext[1] == this->Extent[1]) &&
        (ext[2] == this->Extent[2]) && (ext[3] == this->Extent[3]) &&
        (ext[4] == this->Extent[4]) && (ext[5] == this->Extent[5]) ))
    {
    this->SetPreviousInput(this->Input);
    this->ParallelScale = cam->GetParallelScale();
    this->SetActorScale(scale);
    this->SetViewportSize(size);
    this->SetExtent(ext);

    this->ComputeLabelPositions(viewport);
    }

  int renderedSomething = 0;
  vtkCellLabelAnnotationInternals::CellLabelActorsType::iterator it =
    this->Internal->CellLabelActors.begin();
  vtkTextActor *actor;

  for (; it != this->Internal->CellLabelActors.end(); it++)
    {
    actor = *it;
    // actors were added to the renderer in ComputeLabelPositions
    renderedSomething += actor->RenderOpaqueGeometry(viewport);
    }

  return renderedSomething;
}

//----------------------------------------------------------------------------
void vtkCellLabelAnnotation::ComputeLabelPositions(vtkViewport *viewport)
{
  if ( ! (this->Input && this->DataActor))
    {
    return;
    }

  this->Internal->CellLabelActors.clear();

  if ((this->Extent[0] != this->Extent[1]) &&
      (this->Extent[2] != this->Extent[3]) &&
      (this->Extent[4] != this->Extent[5]))
    {
    vtkErrorMacro("Input is required to be 2D.");
    return;
    }

  // Determine which 2 dimensions are used.
  int dim[3], i;
  this->Input->GetDimensions(dim);
  double corners[4][4];
  int slowDim, fastDim, slowInc, fastInc;
  if (this->Extent[0] == this->Extent[1])
    {
    this->MissingDimension = 0; // x axis
    // Of the remaining 2 axis, along which dimensions do the point / cell ids
    // change faster?
    slowDim = 2; // z axis
    fastDim = 1; // y axis
    slowInc = dim[0]*dim[1];
    fastInc = dim[0];
    }
  else if (this->Extent[2] == this->Extent[3])
    {
    this->MissingDimension = 1; // y axis
    slowDim = 2; // z axis
    fastDim = 0; // x axis
    slowInc = dim[0]*dim[1];
    fastInc = 1;
    }
  else
    {
    this->MissingDimension = 2; // z axis
    slowDim = 1; // y axis
    fastDim = 0; // x axis
    slowInc = dim[0];
    fastInc = 1;
    }

  corners[0][3] = corners[1][3] = corners[2][3] = corners[3][3] = 1;

  // Store the coordinates of the 4 corners of the 2D slice.
  // min slow, min fast
  this->GetWorldPoint(this->Extent[2*slowDim], slowInc,
                      this->Extent[2*fastDim], fastInc, corners[0]);
  corners[0][0] *= this->ActorScale[0];
  corners[0][1] *= this->ActorScale[1];
  corners[0][2] *= this->ActorScale[2];
  // max slow, min fast
  this->GetWorldPoint(this->Extent[2*slowDim+1], slowInc,
                      this->Extent[2*fastDim], fastInc, corners[1]);
  corners[1][0] *= this->ActorScale[0];
  corners[1][1] *= this->ActorScale[1];
  corners[1][2] *= this->ActorScale[2];
  // min slow, max fast
  this->GetWorldPoint(this->Extent[2*slowDim], slowInc,
                      this->Extent[2*fastDim+1], fastInc, corners[2]);
  corners[2][0] *= this->ActorScale[0];
  corners[2][1] *= this->ActorScale[1];
  corners[2][2] *= this->ActorScale[2];
  // max slow, max fast
  this->GetWorldPoint(this->Extent[2*slowDim+1], slowInc,
                      this->Extent[2*fastDim+1], fastInc, corners[3]);
  corners[3][0] *= this->ActorScale[0];
  corners[3][1] *= this->ActorScale[1];
  corners[3][2] *= this->ActorScale[2];

  // Determine closest point to the origin ((0, 0) in display coordinates).
  double closest[3], dispCoord[3], minDist, dist, prevDispCoord[3];
  float floatSize[2];
  int *size = viewport->GetSize(), closestIdx = -1;
  floatSize[0] = size[0];
  floatSize[1] = size[1];
  minDist = vtkMath::Norm(floatSize, 2);

  for (i = 0; i < 4; i++)
    {
    viewport->SetWorldPoint(corners[i]);
    viewport->WorldToDisplay();
    viewport->GetDisplayPoint(dispCoord);
    dist = vtkMath::Norm(dispCoord);
    if (dist < minDist)
      {
      closest[0] = corners[i][0];
      closest[1] = corners[i][1];
      closest[2] = corners[i][2];
      minDist = dist;
      closestIdx = i;
      prevDispCoord[0] = dispCoord[0];
      prevDispCoord[1] = dispCoord[1];
      prevDispCoord[2] = dispCoord[2];
      }
    }

  // determine the indices of the slow and fast axes
  int slowCoord, fastCoord, slowCoord2, fastCoord2;
  if (closestIdx == 0 || closestIdx == 2)
    {
    slowCoord = this->Extent[2*slowDim];
    slowCoord2 = slowCoord+1;
    }
  else
    {
    slowCoord = this->Extent[2*slowDim + 1];
    slowCoord2 = slowCoord-1;
    }
  if (closestIdx < 2)
    {
    fastCoord = this->Extent[2*fastDim];
    fastCoord2 = fastCoord+1;
    }
  else
    {
    fastCoord = this->Extent[2*fastDim+1];
    fastCoord2 = fastCoord-1;
    }

  this->SetupActors(this->Extent[2*fastDim], this->Extent[2*fastDim+1],
                    slowInc, fastInc, slowCoord, slowCoord2, 0, viewport);
  this->SetupActors(this->Extent[2*slowDim], this->Extent[2*slowDim+1],
                    slowInc, fastInc, fastCoord, fastCoord2, 1, viewport);
}

//----------------------------------------------------------------------------
void vtkCellLabelAnnotation::SetupActors(int idxMin, int idxMax,
                                         int slowInc, int fastInc,
                                         int constantCoord, int constantCoord2,
                                         int currentAxis,
                                         vtkViewport *viewport)
{
  double minWorldPoint1[4], minWorldPoint2[4];
  double maxWorldPoint1[4], maxWorldPoint2[4];
  double newWorldPoint[4], dist, dist2;
  double minDispCoord1[3], maxDispCoord1[3];
  double minDispCoord2[3], maxDispCoord2[3];
  double prevDispCoord1[3], prevDispCoord2[3];
  double nextDispCoord1[3], nextDispCoord2[3];
  prevDispCoord1[0] = prevDispCoord1[1] = prevDispCoord1[2] = 0;
  prevDispCoord2[0] = prevDispCoord2[1] = prevDispCoord2[2] = 0;
  int i, j;
  
  // Get world points for axis endpoints.
  minWorldPoint1[3] = minWorldPoint2[3] = maxWorldPoint1[3] =
    maxWorldPoint2[3] = newWorldPoint[3] = 1;

  if (currentAxis == 0)
    {
    this->GetWorldPoint(constantCoord, slowInc, idxMin, fastInc, minWorldPoint1);
    this->GetWorldPoint(constantCoord2, slowInc, idxMin, fastInc, minWorldPoint2);
    this->GetWorldPoint(constantCoord, slowInc, idxMax, fastInc, maxWorldPoint1);
    this->GetWorldPoint(constantCoord2, slowInc, idxMax, fastInc, maxWorldPoint2);
    }
  else
    {
    this->GetWorldPoint(idxMin, slowInc, constantCoord, fastInc, minWorldPoint1);
    this->GetWorldPoint(idxMin, slowInc, constantCoord2, fastInc, minWorldPoint2);
    this->GetWorldPoint(idxMax, slowInc, constantCoord, fastInc, maxWorldPoint1);
    this->GetWorldPoint(idxMax, slowInc, constantCoord2, fastInc, maxWorldPoint2);
    }
  // Scale axis endpoints in world space
  this->ScaleWorldPoint(minWorldPoint1);
  this->ScaleWorldPoint(minWorldPoint2);
  this->ScaleWorldPoint(maxWorldPoint1);
  this->ScaleWorldPoint(maxWorldPoint2);

  // Transform the scaled points from world to display coordinates.
  this->WorldToDisplay(minWorldPoint1, minDispCoord1, viewport);
  this->WorldToDisplay(minWorldPoint2, minDispCoord2, viewport);
  this->WorldToDisplay(maxWorldPoint1, maxDispCoord1, viewport);
  this->WorldToDisplay(maxWorldPoint2, maxDispCoord2, viewport);

  // move the display coordinates out from the edge of the dataset
  this->MoveDisplayCoordinateFromEdge(minDispCoord1, minDispCoord2);
  this->MoveDisplayCoordinateFromEdge(maxDispCoord1, maxDispCoord2);

  // add cell labels starting at the endpoints of the axis and working
  // towards the middle, making sure to keep the labels "far enough" apart
  for (i = idxMin, j = idxMax; i < j; i++, j--)
    {
    if (currentAxis == 0)
      {
      this->GetWorldPoint(constantCoord, slowInc, i+1, fastInc, minWorldPoint1);
      this->GetWorldPoint(constantCoord2, slowInc, i+1, fastInc, minWorldPoint2);
      }
    else
      {
      this->GetWorldPoint(i+1, slowInc, constantCoord, fastInc, minWorldPoint1);
      this->GetWorldPoint(i+1, slowInc, constantCoord2, fastInc, minWorldPoint2);
      }

    this->ScaleWorldPoint(minWorldPoint1);
    this->ScaleWorldPoint(minWorldPoint2);

    this->WorldToDisplay(minWorldPoint1, nextDispCoord1, viewport);
    this->WorldToDisplay(minWorldPoint2, nextDispCoord2, viewport);

    // move the display coordinates out from the edge of the dataset
    this->MoveDisplayCoordinateFromEdge(nextDispCoord1, nextDispCoord2);

    // average this display coordinate with the previous one to determine
    // the position in display coordinates of the label
    minDispCoord1[0] = (minDispCoord1[0] + nextDispCoord1[0])/2;
    minDispCoord1[1] = (minDispCoord1[1] + nextDispCoord1[1])/2;
    minDispCoord1[2] = (minDispCoord1[2] + nextDispCoord1[2])/2;

    dist =
      sqrt(static_cast<double>(
             vtkMath::Distance2BetweenPoints(prevDispCoord1, minDispCoord1)));
    dist2 =
      sqrt(static_cast<double>(
             vtkMath::Distance2BetweenPoints(prevDispCoord2, minDispCoord1)));

    // if the label is "far enough" away from the other labels already
    // added, add an actor for it
    if ((dist > VTK_MIN_DISTANCE_BETWEEN_LABELS &&
         dist2 > VTK_MIN_DISTANCE_BETWEEN_LABELS) || i == idxMin)
      {
      this->DisplayToWorld(minDispCoord1, newWorldPoint, viewport);
      
      this->AddActorToList(newWorldPoint, i);

      memcpy(prevDispCoord1, minDispCoord1, 3*sizeof(double));
      memcpy(minDispCoord1, nextDispCoord1, 3*sizeof(double));
      }

    // same thing from the other end
    if (currentAxis == 0)
      {
      this->GetWorldPoint(constantCoord, slowInc, j-1, fastInc, maxWorldPoint1);
      this->GetWorldPoint(constantCoord2, slowInc, j-1, fastInc, maxWorldPoint2);
      }
    else
      {
      this->GetWorldPoint(j-1, slowInc, constantCoord, fastInc, maxWorldPoint1);
      this->GetWorldPoint(j-1, slowInc, constantCoord2, fastInc, maxWorldPoint2);
      }

    this->ScaleWorldPoint(maxWorldPoint1);
    this->ScaleWorldPoint(maxWorldPoint2);

    this->WorldToDisplay(maxWorldPoint1, nextDispCoord1, viewport);
    this->WorldToDisplay(maxWorldPoint2, nextDispCoord2, viewport);

    this->MoveDisplayCoordinateFromEdge(nextDispCoord1, nextDispCoord2);

    maxDispCoord1[0] = (maxDispCoord1[0] + nextDispCoord1[0])/2;
    maxDispCoord1[1] = (maxDispCoord1[1] + nextDispCoord1[1])/2;
    maxDispCoord1[2] = (maxDispCoord1[2] + nextDispCoord1[2])/2;

    dist =
      sqrt(static_cast<double>(
             vtkMath::Distance2BetweenPoints(prevDispCoord1, maxDispCoord1)));
    dist2 =
      sqrt(static_cast<double>(
             vtkMath::Distance2BetweenPoints(prevDispCoord2, maxDispCoord1)));

    if ((dist > VTK_MIN_DISTANCE_BETWEEN_LABELS &&
         dist2 > VTK_MIN_DISTANCE_BETWEEN_LABELS) || j == idxMax)
      {
      this->DisplayToWorld(maxDispCoord1, newWorldPoint, viewport);
      
      this->AddActorToList(newWorldPoint, j-1);

      memcpy(prevDispCoord2, maxDispCoord1, 3*sizeof(double));
      memcpy(maxDispCoord1, nextDispCoord1, 3*sizeof(double));
      }
    }
}

//----------------------------------------------------------------------------
void vtkCellLabelAnnotation::GetWorldPoint(int slowCoord, int slowInc,
                                           int fastCoord, int fastInc,
                                           double point[3])
{
  switch (this->MissingDimension)
    {
    case 0:
      slowCoord -= this->Extent[4];
      fastCoord -= this->Extent[2];
      break;
    case 1:
      slowCoord -= this->Extent[4];
      fastCoord -= this->Extent[0];
      break;
    case 2:
      slowCoord -= this->Extent[2];
      fastCoord -= this->Extent[0];
      break;
    default:
      break;
    }

  this->Input->GetPoint(slowCoord * slowInc + fastCoord * fastInc, point);
}

//----------------------------------------------------------------------------
void vtkCellLabelAnnotation::ScaleWorldPoint(double point[3])
{
  point[0] *= this->ActorScale[0];
  point[1] *= this->ActorScale[1];
  point[2] *= this->ActorScale[2];
}

//----------------------------------------------------------------------------
void vtkCellLabelAnnotation::WorldToDisplay(double worldPoint[4],
                                            double displayPoint[3],
                                            vtkViewport *viewport)
{
  viewport->SetWorldPoint(worldPoint);
  viewport->WorldToDisplay();
  viewport->GetDisplayPoint(displayPoint);
}

//----------------------------------------------------------------------------
void vtkCellLabelAnnotation::DisplayToWorld(double displayPoint[3],
                                            double worldPoint[4],
                                            vtkViewport *viewport)
{
  viewport->SetDisplayPoint(displayPoint);
  viewport->DisplayToWorld();
  viewport->GetWorldPoint(worldPoint);
}

//----------------------------------------------------------------------------
void vtkCellLabelAnnotation::MoveDisplayCoordinateFromEdge(double coord1[3],
                                                           double coord2[3])
{
  double direction[3];
  direction[0] = coord1[0] - coord2[0];
  direction[1] = coord1[1] - coord2[1];
  direction[2] = coord1[2] - coord2[2];
  if (vtkMath::Normalize(direction) != 0)
    {
    coord1[0] += VTK_NUMBER_OF_PIXELS_FROM_EDGE * direction[0];
    coord1[1] += VTK_NUMBER_OF_PIXELS_FROM_EDGE * direction[1];
    coord1[2] += VTK_NUMBER_OF_PIXELS_FROM_EDGE * direction[2];
    }
}

//----------------------------------------------------------------------------
void vtkCellLabelAnnotation::AddActorToList(double point[3], int idx)
{
  vtkTextActor *actor = vtkTextActor::New();
  actor->GetTextProperty()->BoldOn();

  vtksys_ios::ostringstream label;
  label << idx;

  actor->SetInput(label.str().c_str());
  actor->GetPositionCoordinate()->SetCoordinateSystemToWorld();
  actor->GetPositionCoordinate()->SetValue(point);
  this->Internal->CellLabelActors.push_back(actor);

  actor->Delete();
}

//----------------------------------------------------------------------------
void vtkCellLabelAnnotation::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}
