/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
 *
 * Visit http://camitk.imag.fr for more information
 *
 * This file is part of CamiTK.
 *
 * CamiTK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * CamiTK is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $CAMITK_LICENCE_END$
 ****************************************************************************/
// CamiTK includes
#include "SmoothFilter.h"
#include <Application.h>
#include <Property.h>

// Vtk includes
#include <vtkSmoothPolyDataFilter.h>
#include <vtkSmartPointer.h>
#include <vtkCallbackCommand.h>

using namespace camitk;


// --------------- Constructor -------------------
SmoothFilter::SmoothFilter(ActionExtension* extension) : Action(extension) {
    // Setting name, description and input component
    setName("Smooth Filter");
    setDescription(tr("This filter adjusts point positions using Laplacian smoothing. <br/>It makes the cells better shaped and the vertices more evenly distributed. <br /> The effect is to \"relax\" the mesh, making the cells better shaped and the vertices more evenly distributed. Note that this filter operates on the lines, polygons, and triangle strips composing an instance of vtkPolyData. Vertex or poly-vertex cells are never modified. <br /><br />\
                      The algorithm proceeds as follows. For each vertex v, a topological and geometric analysis is performed to determine which vertices are connected to v, and which cells are connected to v. Then, a connectivity array is constructed for each vertex. (The connectivity array is a list of lists of vertices that directly attach to each vertex.) Next, an iteration phase begins over all vertices. For each vertex v, the coordinates of v are modified according to an average of the connected vertices. (A relaxation factor is available to control the amount of displacement of v). The process repeats for each vertex. This pass over the list of vertices is a single iteration. Many iterations (generally around 20 or so) are repeated until the desired result is obtained. <br/><br/> \
                      There are some special parameters used to control the execution of this filter. (These parameters basically control what vertices can be smoothed, and the creation of the connectivity array.) The <b>Boundary smoothing</b> paramerter enables/disables the smoothing operation on vertices that are on the \"boundary\" of the mesh. A boundary vertex is one that is surrounded by a semi-cycle of polygons (or used by a single line). <br/><br/>\
                      Another important parameter is <b>Feature edge smoothing</b>. If this ivar is enabled, then interior vertices are classified as either \"simple\", \"interior edge\", or \"fixed\", and smoothed differently. (Interior vertices are manifold vertices surrounded by a cycle of polygons; or used by two line cells.) The classification is based on the number of feature edges attached to v. A feature edge occurs when the angle between the two surface normals of a polygon sharing an edge is greater than the FeatureAngle ivar. Then, vertices used by no feature edges are classified \"simple\", vertices used by exactly two feature edges are classified \"interior edge\", and all others are \"fixed\" vertices.<br/><br/> \
                      Once the classification is known, the vertices are smoothed differently. Corner (i.e., fixed) vertices are not smoothed at all. Simple vertices are smoothed as before (i.e., average of connected vertex coordinates). Interior edge vertices are smoothed only along their two connected edges, and only if the angle between the edges is less than the EdgeAngle ivar.<br/><br/>\
                      The total smoothing can be controlled by the <b>The Number of iterations</b> which is a cap on the maximum number of smoothing passes.<br/><br/>\
                      Note that this action does not create a new component, but modify the selected one(s)."));


    setComponentClassName("MeshComponent");

    // Setting classification family and tags
    setFamily("Mesh Processing");
    addTag(tr("SMO"));

    // Setting the action's parameters
    Property* boundarySmoothingProperty = new Property(tr("Boundary smoothing"), true, tr("Turn on/off the smoothing of vertices on the boundary of the mesh."), "");
    addParameter(boundarySmoothingProperty);

    Property* featureEdgeSmoothingProperty = new Property(tr("Feature edge smoothing"), false, tr("Turn on/off smoothing along sharp interior edges."), "");
    addParameter(featureEdgeSmoothingProperty);

    Property* numberOfIterationProperty = new Property(tr("Number of iterations"), 20, tr("Specify the number of iterations for Laplacian smoothing."), "");
    numberOfIterationProperty->setAttribute("minimum", 1);
    numberOfIterationProperty->setAttribute("singleStep", 1);
    addParameter(numberOfIterationProperty);

    Property* edgeAngleProperty = new Property(tr("Edge angle"), 15.0, tr("Specify the edge angle to control smoothing along edges (either interior or boundary)."), "Degrees");
    edgeAngleProperty->setAttribute("minimum", 0.0);
    edgeAngleProperty->setAttribute("maximum", 359.0);
    edgeAngleProperty->setAttribute("singleStep", 0.1);
    addParameter(edgeAngleProperty);

    Property* featureAngleProperty = new Property(tr("Feature angle"), 45.0, tr("Specify the feature angle for sharp edge identification."), "Degrees");
    featureAngleProperty->setAttribute("minimum", 0.0);
    featureAngleProperty->setAttribute("maximum", 359.0);
    featureAngleProperty->setAttribute("singleStep", 0.1);
    addParameter(featureAngleProperty);

    Property* relaxationProperty = new Property(tr("Relaxation factor"), 0.1, tr("Specify the relaxation factor for Laplacian smoothing. <br/> As in all iterative methods, the stability of the process is sensitive to this parameter. In general, small relaxation factors and large numbers of iterations are more stable than larger relaxation factors and smaller numbers of iterations."), "");
    relaxationProperty->setAttribute("minimum", 0.0);
    relaxationProperty->setAttribute("singleStep", 0.1);
    addParameter(relaxationProperty);
}

// --------------- destructor -------------------
SmoothFilter::~SmoothFilter() {
    // Do not do anything yet.
    // Delete stuff if you create stuff
    // (except if you use smart pointers of course !!)
}

// --------------- apply -------------------
Action::ApplyStatus SmoothFilter::apply() {
    for (Component* comp : getTargets()) {
        MeshComponent* input = dynamic_cast<MeshComponent*>(comp);
        process(input);
    }
    return SUCCESS;
}

// --------------- apply -------------------
void SmoothFilter::process(MeshComponent* comp) {
    // Get the parameters
    bool boundarySmoothing = getParameterValue("Boundary smoothing").toBool();
    double edgeAngle = getParameterValue("Edge angle").toDouble();
    bool edgeSmoothing = getParameterValue("Feature edge smoothing").toBool();
    double featureAngle = getParameterValue("Feature angle").toDouble();
    int iteration = getParameterValue("Number of iterations").toInt();
    double relaxation = getParameterValue("Relaxation factor").toDouble();

    vtkSmartPointer<vtkCallbackCommand> progressCallback = vtkSmartPointer<vtkCallbackCommand>::New();
    progressCallback->SetCallback(&Application::vtkProgressFunction);

    vtkSmartPointer<vtkPolyData> poly = vtkPolyData::SafeDownCast(comp->getPointSet());

    // create the filter and set the polydata
    vtkSmartPointer<vtkSmoothPolyDataFilter> smoothFilter = vtkSmartPointer<vtkSmoothPolyDataFilter>::New();
    smoothFilter->SetInputData(poly);
    // set the number of iterations
    smoothFilter->SetNumberOfIterations(iteration);
    // set the relaxation factor
    smoothFilter->SetRelaxationFactor(relaxation);
    // a small relaxation and a  large number of iterations are more stable than a large relaxation factor and a small number of iterations

    // turn on/off the smoothing of vertices on the boundary of the mesh.
    if (!boundarySmoothing) {
        smoothFilter->SetBoundarySmoothing(0);
    }
    // set angles
    smoothFilter->SetFeatureAngle(featureAngle);
    smoothFilter->SetEdgeAngle(edgeAngle);
    // turn on/off smoothing along sharp interior edges.
    if (edgeSmoothing) {
        smoothFilter->SetFeatureEdgeSmoothing(1);
    }
    smoothFilter->AddObserver(vtkCommand::ProgressEvent, progressCallback);
    smoothFilter->Update();

    comp->setPointSet(vtkPointSet::SafeDownCast(smoothFilter->GetOutput()));
    comp->refresh();

    // restore the normal cursor and progress bar
    Application::resetProgressBar();
    QApplication::restoreOverrideCursor();
}


