/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2008.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: src/sgx/input/controlstick.cpp

*/

#include "sgx/core/core.hpp"
#include "sgx/input/input.hpp"

CSGXInputManager::CControlStick::CControlStick()
{
	setControlRange(100.0f);
	setDeadZone(3.0f);
	setClampX(-1, 1);
	setClampY(-1, 1);
	reset();
}

void 
CSGXInputManager::CControlStick::setDeadZone(const tREAL32 range) {
	m_fGivenDeadZone = range;
	m_fDeadZone = m_fGivenDeadZone/m_fControlRangeX;
}

void 
CSGXInputManager::CControlStick::setControlRange(const tREAL32 range) {
	setControlRange(range, range);
}

void 
CSGXInputManager::CControlStick::setControlRange(const tREAL32 rangeX, const tREAL32 rangeY) {
	m_fControlRangeX = rangeX;
	m_fControlRangeY = rangeY;
	m_fScaleRangeX = m_fControlRangeX - m_fDeadZone;
	m_fScaleRangeY = m_fControlRangeY - m_fDeadZone;
	m_fDeadZone = m_fGivenDeadZone/m_fControlRangeX;
}


void 
CSGXInputManager::CControlStick::setClampX(const tREAL32 minX, const tREAL32 maxX) {
	m_fClampMinX = minX;
	m_fClampMaxX = maxX;
}

void 
CSGXInputManager::CControlStick::setClampY(const tREAL32 minY, const tREAL32 maxY) {
	m_fClampMinY = minY;
	m_fClampMaxY = maxY;
}

void 
CSGXInputManager::CControlStick::reset()
{
	m_fPosX = m_fPosY = 0;
	m_fRawPosX = m_fRawPosY = 0;
}

void 
CSGXInputManager::CControlStick::update(const tREAL32 telaps)
{
	SGX_UNUSED(telaps);
}

void 
CSGXInputManager::CControlStick::applyPosition(const tREAL32 x, const tREAL32 y)
{
	m_fPosX = m_fRawPosX = x;
	m_fPosY = m_fRawPosY = y;

	// Incorporate deadzone
	// And pull in edges so deadzone=>0, and deadzone+1=>1 etc
	if (x > -m_fDeadZone && x < m_fDeadZone) {
		m_fPosX = 0;
	} else if (x < 0) {
		m_fPosX += m_fDeadZone;
		m_fPosX /= m_fScaleRangeX;
	} else if (x > 0) {
		m_fPosX -= m_fDeadZone;
		m_fPosX /= m_fScaleRangeX;
	}
	//
	if (y > -m_fDeadZone && y < m_fDeadZone) {
		m_fPosY = 0;
	} else if (y < 0) {
		m_fPosY += m_fDeadZone;
		m_fPosY /= m_fScaleRangeY;
	} else if (y > 0) {
		m_fPosY -= m_fDeadZone;
		m_fPosY /= m_fScaleRangeY;
	}
	//
	m_fPosX = sgxRange(m_fPosX, m_fClampMinX, m_fClampMaxX);
	m_fPosY = sgxRange(m_fPosY, m_fClampMinY, m_fClampMaxY);
}

