/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
    \\  /    A nd           | www.openfoam.com
     \\/     M anipulation  |
-------------------------------------------------------------------------------
    Copyright (C) 2019 OpenFOAM Foundation
    Copyright (C) 2020 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

    OpenFOAM is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    OpenFOAM 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 General Public License
    for more details.

    You should have received a copy of the GNU General Public License
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

\*---------------------------------------------------------------------------*/

#include "angleControlWave2COM.H"
#include "rigidBodyModel.H"
#include "rigidBodyModelState.H"
#include "OneConstant.H"
#include "addToRunTimeSelectionTable.H"

//#include "rigidBodyMotion.H"

#define	deg(a)	((a)*180.0/3.141592)	// from rad to deg

// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //

namespace Foam
{
namespace RBD
{
namespace restraints
{
    defineTypeNameAndDebug(angleControlWave2COM, 0);

    addToRunTimeSelectionTable
    (
        restraint,
        angleControlWave2COM,
        dictionary
    );
}
}
}


// * * * * * * * * * * * * * * * * Constructors  * * * * * * * * * * * * * * //

Foam::RBD::restraints::angleControlWave2COM::angleControlWave2COM
(
    const word& name,
    const dictionary& dict,
    const rigidBodyModel& model
)
:
    restraint(name, dict, model),
    parameters_(Tensor<scalar>::zero),
    x_axis_(Tensor<scalar>::zero),
    y_axis_(Tensor<scalar>::zero),
    z_axis_(Tensor<scalar>::zero)
{
    read(dict);
}


// * * * * * * * * * * * * * * * * Destructor  * * * * * * * * * * * * * * * //

Foam::RBD::restraints::angleControlWave2COM::~angleControlWave2COM()
{}


// * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * * //

Foam::vector Foam::RBD::restraints::angleControlWave2COM::RodriguesVectorFromMatrix
(
    const Tensor<scalar> R
) const
{
    vector	n(0,0,0);
    scalar	xx, yy, theta;
    yy = sqrt( sqr(R.xy()-R.yx()) + sqr(R.xz()-R.zx()) + sqr(R.yz()-R.zy()) ) / 2.0;
    xx = ( R.xx() + R.yy() + R.zz() - 1 ) / 2.0;

    theta = Foam::atan2( yy, xx );

    if( mag(theta) < (100*VSMALL) ){	// theta = 0 deg.
	n = Zero;
    }else if( mag( mag(theta) - mag(Foam::atan2(0.0,-1.0)) ) < (100*VSMALL) ){	// theta = +-180 deg.
	if( (R.xx()+1) < 0.0 ) 	n[0] = 0.0;
	else			n[0] = sqrt( (R.xx() + 1)/2.0 );
	if( (R.yy()+1) < 0.0 )  n[1] = 0.0;
	else{
	  if( R.yx() > 0 )	n[1] = sqrt( (R.yy() + 1)/2.0 );
	  else			n[1] =-sqrt( (R.yy() + 1)/2.0 );
	}
	if( (R.zz()+1) < 0.0 )	n[2] = 0.0;
	else{
	  if( R.zx() > 0 )	n[2] = sqrt( (R.zz() + 1)/2.0 );
	  else			n[2] =-sqrt( (R.zz() + 1)/2.0 );
	}
	n *= theta;

// Info << " theta*n " << n << endl;


    }else{
	n[0] = -(R.yz()-R.zy()) / (2.0*sin(theta));
	n[1] =  (R.xz()-R.zx()) / (2.0*sin(theta));
	n[2] = -(R.xy()-R.yx()) / (2.0*sin(theta));
	n *= theta;
    }

    return	n;
}

void Foam::RBD::restraints::angleControlWave2COM::restrain
(
    scalarField& tau,
    Field<spatialVector>& fx,
    const rigidBodyModelState& state
) const
{
//	Info << "angleControlWave2COM: " << endl;

	label referenceID = model_.bodyID(reaction_);				// reaction_ means a rigid body name  
    	const double Pgain = parameters_.xx(), Dgain = parameters_.xy(), Maxgain = parameters_.xz();
	const double order = parameters_.yx(), relaxation_time = parameters_.yy(), t = state.t(), dt = state.deltaT();
	double xangle = x_axis_.xx() * sin( 2.0*3.141592 * x_axis_.xy() * t + x_axis_.xz() ) +  x_axis_.yx();
	double yangle = y_axis_.xx() * sin( 2.0*3.141592 * y_axis_.xy() * t + y_axis_.xz() ) +  y_axis_.yx();
	double zangle = z_axis_.xx() * sin( 2.0*3.141592 * z_axis_.xy() * t + z_axis_.xz() ) +  z_axis_.yx();
	double preXangle = x_axis_.xx() * sin( 2.0*3.141592 * x_axis_.xy() * (t-dt) + x_axis_.xz() ) +  x_axis_.yx();
	double preYangle = y_axis_.xx() * sin( 2.0*3.141592 * y_axis_.xy() * (t-dt) + y_axis_.xz() ) +  y_axis_.yx();
	double preZangle = z_axis_.xx() * sin( 2.0*3.141592 * z_axis_.xy() * (t-dt) + z_axis_.xz() ) +  z_axis_.yx();

	Tensor<scalar> Rx, Ry, Rz, targetR, preR;
	Rx.xx() = 1.0;		Rx.yx() = 0.0;		Rx.zx() = 0.0;
	Rx.xy() = 0.0;		Rx.yy() = cos(xangle);	Rx.zy() =-sin(xangle);
	Rx.xz() = 0.0;		Rx.yz() = sin(xangle);	Rx.zz() = cos(xangle);

	Ry.xx() = cos(yangle);	Ry.yx() = 0.0;		Ry.zx() = sin(yangle);
	Ry.xy() = 0.0;		Ry.yy() = 1.0;		Ry.zy() = 0.0;
	Ry.xz() =-sin(yangle);	Ry.yz() = 0.0;		Ry.zz() = cos(yangle);

	Rz.xx() = cos(zangle);	Rz.yx() =-sin(zangle);	Rz.zx() = 0.0;
	Rz.xy() = sin(zangle);	Rz.yy() = cos(zangle);	Rz.zy() = 0.0;
	Rz.xz() = 0.0;		Rz.yz() = 0.0;		Rz.zz() = 1.0;

	if( order < 0.5 )	targetR = Rx & Ry & Rz;
	else			targetR = Rz & Ry & Rx;
	
	Rx.xx() = 1.0;		Rx.yx() = 0.0;			Rx.zx() = 0.0;
	Rx.xy() = 0.0;		Rx.yy() = cos(preXangle);	Rx.zy() =-sin(preXangle);
	Rx.xz() = 0.0;		Rx.yz() = sin(preXangle);	Rx.zz() = cos(preXangle);

	Ry.xx() = cos(preYangle);	Ry.yx() = 0.0;		Ry.zx() = sin(preYangle);
	Ry.xy() = 0.0;			Ry.yy() = 1.0;		Ry.zy() = 0.0;
	Ry.xz() =-sin(preYangle);	Ry.yz() = 0.0;		Ry.zz() = cos(preYangle);

	Rz.xx() = cos(preZangle);	Rz.yx() =-sin(preZangle);	Rz.zx() = 0.0;
	Rz.xy() = sin(preZangle);	Rz.yy() = cos(preZangle);	Rz.zy() = 0.0;
	Rz.xz() = 0.0;			Rz.yz() = 0.0;			Rz.zz() = 1.0;

	if( order < 0.5 )	preR = Rx & Ry & Rz;
	else			preR = Rz & Ry & Rx;

	/*** target angle ***/
	Tensor<scalar> Rr = model_.X0(referenceID).E().T(), Rb = model_.X0(bodyID_).E().T();
	Tensor<scalar> rRb = Rr.T() & Rb;

	Tensor<scalar> bRtarget;
	bRtarget = rRb & targetR; 
	vector momentP = RodriguesVectorFromMatrix( bRtarget );

	/*** target anglular velocity ***/
	vector angular_vel = Rr.T() & ( model_.v(bodyID_).w() - model_.v(referenceID).w() );

	Tensor<scalar> preRtarget;
	preRtarget = preR & targetR; 
	vector momentD = RodriguesVectorFromMatrix( preRtarget );
	momentD /= dt;

	vector moment = Pgain * momentP + Dgain * ( momentD - angular_vel );

	if( t < relaxation_time  )	moment *= (t/relaxation_time);
	
	if( Maxgain < mag( moment ) )	moment *= ( Maxgain / mag( moment ) );

    if( model_.debug )
//    if ( RBD::rigidBodyMotion::Iteration_number_for_MB_ == 0 )
    {
	Info<< " angleControlWave2COM: " << endl
	<< model_.name(bodyID_) << "["<< bodyID_ << ", " << bodyIndex_ << "], " << reaction_ << "[" <<referenceID << "]" << endl
	<< "target x angle = " << deg(xangle) << " y angle = " << deg(yangle) << " z angle = " << deg(zangle) << ", t= " << t << endl;

	Info << "angle difference: " << mag(momentP) << " angular velocity difference " << mag(momentD - angular_vel) << endl;
	Info << "moment: " << moment << " P " << mag(Pgain * momentP) << " D " << mag(Dgain * ( momentD - angular_vel )) << endl;

	if( ( referenceID == 0 ) || ( bodyID_ == 0 ) )	Info << "The moment is not reacted to the root" << endl;
    }

    // Accumulate the ONLY MOMENT for the restrained body
    if( bodyIndex_ != 0 )	fx[bodyIndex_]  += spatialVector( Rr & moment, Zero /*force*/ );
    if( referenceID != 0 )	fx[referenceID] -= spatialVector( Rr & moment, Zero /*force*/ );
}


bool Foam::RBD::restraints::angleControlWave2COM::read
(
    const dictionary& dict
)
{
    restraint::read(dict);

    coeffs_.readEntry("parameters", parameters_);
    coeffs_.readEntry("reaction", reaction_);
    coeffs_.readEntry("x_axis", x_axis_);
    coeffs_.readEntry("y_axis", y_axis_);
    coeffs_.readEntry("z_axis", z_axis_);

    return true;
}


void Foam::RBD::restraints::angleControlWave2COM::write
(
    Ostream& os
) const
{
    restraint::write(os);

    os.writeEntry("parameters", parameters_);
    os.writeEntry("reaction", reaction_);
    os.writeEntry("x_axis", x_axis_);
    os.writeEntry("y_axis", y_axis_);
    os.writeEntry("z_axis", z_axis_);
}


// ************************************************************************* //
