/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  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 "angularVelocityControlCOM.H"
#include "rigidBodyModel.H"
#include "rigidBodyModelState.H"
#include "OneConstant.H"
#include "addToRunTimeSelectionTable.H"

// #include "rigidBodyMotion.H"

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

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

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

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


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

Foam::RBD::restraints::angularVelocityControlCOM::angularVelocityControlCOM
(
    const word& name,
    const dictionary& dict,
    const rigidBodyModel& model
)
:
    restraint(name, dict, model)
{
    read(dict);
}


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

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


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

void Foam::RBD::restraints::angularVelocityControlCOM::restrain
(
    scalarField& tau,
    Field<spatialVector>& fx,
    const rigidBodyModelState& state
) const
{
	label referenceID = model_.bodyID(reaction_);				// reaction_ means a rigid body name  
	Tensor<scalar> Rr = model_.X0(referenceID).E().T();
	scalar	t = state.t();
        const vector axis = Rr & ( rotational_axis_ / (mag(rotational_axis_) + VSMALL) );
	scalar angular_vel = ( Rr.T() & ( model_.v(bodyID_).w() - model_.v(referenceID).w() ) ) & axis;
	scalar angular_accel=( Rr.T() & ( model_.a(bodyID_).w() - model_.a(referenceID).w() ) ) & axis;

	// **** rotation control ****
	vector moment = ( gain_[0] * ( angular_velocity_ - angular_vel ) + gain_[1] * ( 0.0 - angular_accel ) ) * axis;

	double	torque = mag( moment );	
	if( gain_[2] < torque )	moment *= ( gain_[2] / torque );

	if( t < relaxation_time_  )	moment *= (t/relaxation_time_);



	// **** axis control ****
	Tensor<scalar> Rb = model_.X0(bodyID_).E().T();
	Tensor<scalar> rRb = Rr.T() & Rb;
	vector r_body_axis = ( rRb & ( rotational_axis_ / (mag(rotational_axis_) + VSMALL) ) );
	vector r_axisk = r_body_axis ^ axis;
	r_axisk /= ( mag(r_axisk) + VSMALL );
	vector r_angular_vel = Rr.T() & ( model_.v(bodyID_).w() - model_.v(referenceID).w() );
	vector r_vectk = axis ^ ( r_angular_vel ^ axis );
	r_vectk /= ( mag(r_vectk) + VSMALL );
	scalar theta;
	if( 1.0 <= ( r_body_axis & axis ) )	theta = 0.0;
	else					theta = acos( r_body_axis & axis );

	vector moment2 = gain2_[0] * theta * r_axisk + gain2_[1] * ( Zero - ( r_angular_vel & r_vectk ) * r_vectk );
	torque = mag( moment2 );	
	if( gain2_[2] < torque )	moment2 *= ( gain2_[2] / torque );




    if ( model_.debug )
    {
	Info << endl << " **** angularVelocityControlCOM: **** " << endl
	<< model_.name(bodyID_) << "["<< bodyID_ << ", " << bodyIndex_ << "], " << reaction_ << "[" <<referenceID << "]" << endl
	<< " angular velocity [deg/s] = " << deg( angular_velocity_ ) << ", " << deg( angular_vel ) << endl 
	<< " angular acceleration [deg/s^2] = 0.0, " << deg( angular_accel ) << endl 
	<< " gain = " << gain_ << ", relaxation time= " << relaxation_time_ << endl;
	Info << "moment = " << moment << ", P= " << gain_[0] * ( angular_velocity_ - angular_vel ) << ", D= " <<  gain_[1] * ( 0.0 - angular_accel ) << endl;

	Info << "axes: Rr*a= " << (Rr & rotational_axis_) << " , Rb*a = " << (Rb & rotational_axis_) << endl;
	Info << "difference[deg] = " << deg( theta ) << endl;
	Info << "difference[deg/s] = " << -deg( r_angular_vel & r_vectk ) << endl
	     << " gain2 = " << gain2_ << endl;

	Info << "moment2 = " << moment2 << ", P= " << gain2_[0] * theta * r_axisk << ", D= " <<  gain2_[1] * ( Zero - ( r_angular_vel & r_vectk ) * r_vectk ) << 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 + moment2 ), Zero /*force*/ );
    if( referenceID != 0 )	fx[referenceID] -= spatialVector( Rr & ( moment + moment2 ), Zero /*force*/ );
}


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

    coeffs_.readEntry("rotational_axis", rotational_axis_);
    coeffs_.readEntry("angular_velocity", angular_velocity_);
    coeffs_.readEntry("gain", gain_);
    coeffs_.readEntry("gain2", gain2_);
    coeffs_.readEntry("relaxation_time", relaxation_time_);
    coeffs_.readEntry("reaction", reaction_);

    return true;
}


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

    os.writeEntry("rotational_axis", rotational_axis_);
    os.writeEntry("angular_velocity", angular_velocity_);
    os.writeEntry("gain", gain_);
    os.writeEntry("gain2", gain2_);
    os.writeEntry("relaxation_time", relaxation_time_);
    os.writeEntry("reaction", reaction_);
}


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