#include "CPhysicsSlider.h"

vector3df CPhysicsSlider::m_breakForce;
f32 CPhysicsSlider::m_minSlide;
f32 CPhysicsSlider::m_maxSlide;

CPhysicsSlider::CPhysicsSlider()
{

}

CPhysicsSlider::~CPhysicsSlider()
{

}

void CPhysicsSlider::init(NewtonWorld* world, SPhysicsSliderJoint* jnt)
{
	m_world = world;
	
	jnt->pivot *= IrrToNewton;
	jnt->pin *= IrrToNewton;
	m_breakForce = jnt->breakForce;

	vector3df size = *(vector3df*)NewtonBodyGetUserData(jnt->parent->getBody());	

	m_minSlide = (jnt->parent->getNode()->getRelativeTransformation().getTranslation().X - size.X * 0.5f) * IrrToNewton;

	m_maxSlide = (jnt->parent->getNode()->getRelativeTransformation().getTranslation().X + size.X * 0.5f) * IrrToNewton;

	m_joint = NewtonConstraintCreateSlider(m_world, &jnt->pivot.X, &jnt->pin.X, jnt->child->getBody(), jnt->parent->getBody());

	NewtonSliderSetUserCallback(m_joint, sliderCallback);
}

void CPhysicsSlider::setUserCallback(NewtonSliderCallBack callback)
{
	NewtonSliderSetUserCallback(m_joint, callback);
}

unsigned CPhysicsSlider::sliderCallback(const NewtonJoint* slider, NewtonHingeSliderUpdateDesc* desc)
{
	if (m_breakForce == vector3df(0,0,0))
		return 0;

	vector3df force;
	NewtonSliderGetJointForce(slider, &force.X);

	if ((force.X > m_breakForce.X) || (force.Y > m_breakForce.Y) || (force.Z > m_breakForce.Z))
		NewtonDestroyJoint(m_world, slider);

	return 0;
}

f32 CPhysicsSlider::getJointAngle()
{
	return NewtonSliderGetJointPosit(m_joint);
}

f32 CPhysicsSlider::getJointVelocity()
{
	return NewtonSliderGetJointVeloc(m_joint);
}

vector3df CPhysicsSlider::getForce()
{
	vector3df force;
	NewtonSliderGetJointForce(m_joint, &force.X);
	return force;
}