/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library 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 *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#ifndef SOFA_COMPONENT_MAPPING_ProjectionToMeshMapping_H
#define SOFA_COMPONENT_MAPPING_ProjectionToMeshMapping_H

#include "initContactMapping.h"
//#include <sofa/component/component.h>
#include <sofa/core/Mapping.h>
#include <sofa/defaulttype/VecTypes.h>
#include <SofaEigen2Solver/EigenSparseMatrix.h>
#include <sofa/core/topology/BaseMeshTopology.h>
#include "projectToMesh.h"

namespace sofa
{

namespace component
{

namespace mapping
{

/**
 * Projecting parent1 points to parent2 (mesh).
 * C_i is the closest vertex on parent2 from P_i in parent1 (provided by closestPointEngine through indexPairs)
 * @warning see ProjectionToMeshEngine to compute "closests"
 *
 * @author Matthieu Nesme, Benjamin Gilles, Thomas Lemaire
 * @date 2016
 */
template <class TIn, class TOut>
class ProjectionToMeshMapping : public core::Mapping<TIn, TOut>
{
public:
    SOFA_CLASS(SOFA_TEMPLATE2(ProjectionToMeshMapping, TIn, TOut), SOFA_TEMPLATE2(core::Mapping, TIn, TOut));

    typedef core::Mapping<TIn, TOut> Inherit;
    typedef TIn In;
    typedef TOut Out;

    typedef typename In::Coord    InCoord;
    typedef typename In::Deriv    InDeriv;
    typedef typename In::VecCoord InVecCoord;
    typedef typename In::VecDeriv InVecDeriv;
    typedef typename Out::Coord   OutCoord;
    typedef typename Out::Deriv   OutDeriv;
    typedef typename Out::VecCoord OutVecCoord;
    typedef typename Out::VecDeriv OutVecDeriv;
    typedef typename OutCoord::value_type Real;

    typedef typename Inherit::InDataVecCoord InDataVecCoord;
    typedef typename Inherit::InDataVecDeriv InDataVecDeriv;
    typedef typename Inherit::InDataMatrixDeriv InDataMatrixDeriv;
    typedef typename Inherit::OutDataVecCoord OutDataVecCoord;
    typedef typename Inherit::OutDataVecDeriv OutDataVecDeriv;
    typedef typename Inherit::OutDataMatrixDeriv OutDataMatrixDeriv;

    enum {Nin = In::deriv_total_size, Nout = Out::deriv_total_size };
    typedef linearsolver::EigenSparseMatrix<In,Out> Jacobian;
    typedef linearsolver::EigenSparseMatrix<In,In> Stiffness;

    typedef typename core::topology::BaseMeshTopology::SeqEdges SeqEdges;
    typedef typename core::topology::BaseMeshTopology::SeqTriangles SeqTriangles;
    typedef typename core::topology::BaseMeshTopology::SeqQuads SeqQuads;

protected:

    ProjectionToMeshMapping();

    virtual ~ProjectionToMeshMapping() {}


public:

    virtual void init();
    virtual void reinit();

    virtual void apply(const core::MechanicalParams* mparams, OutDataVecCoord& out, const InDataVecCoord& in);

    virtual void applyJ(const core::MechanicalParams*, OutDataVecDeriv& outDeriv, const InDataVecDeriv& inDeriv)
    {
        if( m_jacobian.rows() ) // out can be empty if no distance to map
            m_jacobian.mult(outDeriv, inDeriv);
    }

    virtual void applyJT(const core::MechanicalParams*, OutDataVecDeriv& outDeriv , const InDataVecDeriv& inDeriv)
    {
        if( m_jacobian.rows() ) // out can be empty if no distance to map
            m_jacobian.addMultTranspose(outDeriv, inDeriv);
    }
    virtual void applyJT( const core::ConstraintParams*, InDataMatrixDeriv&, const OutDataMatrixDeriv& ) {} // no yet implemented
    virtual void applyDJT( const core::MechanicalParams* /*mparams*/, core::MultiVecDerivId /*parentDfId*/, core::ConstMultiVecDerivId ) {} // no geometric stiffness

    virtual const helper::vector<sofa::defaulttype::BaseMatrix*>* getJs() { return &m_jacobians; }
    virtual const sofa::defaulttype::BaseMatrix* getK() { return  NULL; }


    void draw(const core::visual::VisualParams* vparams);
    virtual void updateForceMask();

    void resizeOut(size_t size);
    Data<helper::vector<defaulttype::Vec2i> > f_indexPairs;    ///< input pairs of correspondences
    Data< std::list<size_t> > d_validPairs; ///< optional list of valid index pairs


    typedef helper::ProjectToMesh<InCoord> ProjectToMesh;
    typedef typename ProjectToMesh::IndexToWeightPair IndexToWeightPair;
    typedef typename ProjectToMesh::ClosestStruct ClosestStruct;
    Data< helper::vector<ClosestStruct> > d_closests; ///< give the closest point on mesh from each parent point (see ProjectionToMeshEngine)
    Data<InVecCoord> d_meshPositions; ///< mesh positions, necessary to compute edge unit vector in all cases

    Data<bool > d_handleBorder; ///< enable stiff (possibly sticky) projection on border?

    Data< Real > d_showObjectScale;     ///< drawing size
    Data< defaulttype::Vec4f > d_color; ///< drawing color

protected:

    Jacobian m_jacobian;
    helper::vector<defaulttype::BaseMatrix*> m_jacobians; ///< Jacobian of the mapping, in a vector
};

#if defined(SOFA_EXTERN_TEMPLATE) && !defined(SOFA_COMPONENT_MAPPING_ProjectionToMeshMapping_CPP)
#ifndef SOFA_FLOAT
extern template class SOFA_ContactMapping_API ProjectionToMeshMapping< sofa::defaulttype::Vec3dTypes, sofa::defaulttype::Vec3dTypes >;
#endif
#ifndef SOFA_DOUBLE
extern template class SOFA_ContactMapping_API ProjectionToMeshMapping< sofa::defaulttype::Vec3fTypes, sofa::defaulttype::Vec3fTypes >;
#endif
#endif

} // namespace mapping

} // namespace component

} // namespace sofa

#endif //SOFA_COMPONENT_MAPPING_ProjectionToMeshMapping_H
