// BlinkGame - Hunt for the Lost Pixels
// an SDL game in honor of the BlinkenArea crew
//
// (C) 2005-06 Rene Schickbauer
//
// See License.txt for licensing information
//
#ifdef NOP_CODE
/*--------------------------------------------------------------------
CVS AUTO-GENERATED INFO
$Author: cavac $
$Date: 2006/02/24 18:48:26 $
$Name: rel-0-3-patches $
$Revision: 1.2 $
$State: Exp $

$Log: joystick.cpp,v $
Revision 1.2  2006/02/24 18:48:26  cavac
Finally added real scripting support
Added Testlevel (level0) which can be enabled from globals.h

Revision 1.1  2006/01/23 18:47:55  cavac
Patches for unix make system for building on Linux  and other
   Unix systems (thanks to: Dauti)
Tests for new colission detection (default: Use old one)
Added Joystick/Gamepad support (only tested with a cheap logitech gamepad)
Fixed some warnings on linux/gcc3
Added true-type fonts for planned menu system
Added library SDL_ttf in xcode for planned menu-system

--------------------------------------------------------------------*/
#endif //NOP_CODE

#include "globals.h"
#include "joystick.h"

// Pointer to the joystick interface
SDL_Joystick *gJoystick = NULL;
bool actionPressed = false;

void initJoystick()
{
	if (SDL_NumJoysticks() > 0)
	{
		gJoystick = SDL_JoystickOpen(0);		
		if (SDL_JoystickNumAxes(gJoystick) < 2)
		{
			// Not enough axes for our use; don't use the joystick.
			SDL_JoystickClose(gJoystick);
			gJoystick = NULL;
		}
	}
	return;
}

void deInitJoystick() 
{
	if (gJoystick) {
		SDL_JoystickClose(gJoystick);
		gJoystick = NULL;
	}
	return;
}

Uint32 getJoystickMoves() {
	Uint32 joymove = JOYSTICK_NONE;
	if(!gJoystick) {
		return joymove;
	}
	
	// Axis are between -32768 and +32768 for analog and digital joysticks. As we just want to check if the
	// player wants to move, we use pseudo-values of about 1/3 of the axis for triggering the move (on analog joysticks relevant only)
	Sint32 xmov = SDL_JoystickGetAxis(gJoystick, 0);
	Sint32 ymov = SDL_JoystickGetAxis(gJoystick, 1);
	
	if(xmov < -10000) {
		joymove += JOYSTICK_LEFT;
	} else if(xmov > 10000) {
		joymove += JOYSTICK_RIGHT;
	}
	
	if(ymov < -10000) {
		joymove += JOYSTICK_UP;
	} else if(ymov > 10000) {
		joymove += JOYSTICK_DOWN;
	}
	
	if(SDL_JoystickNumButtons(gJoystick)>1 && SDL_JoystickGetButton(gJoystick, 1)) {
		joymove = joymove | JOYSTICK_JUMP;
	}
	if(SDL_JoystickNumButtons(gJoystick)>2 && SDL_JoystickGetButton(gJoystick, 2)) {
		if(!actionPressed) {
			joymove = joymove | JOYSTICK_ACTION;
			actionPressed = true;
		}
	} else {
		actionPressed = false;
	}
	
	return joymove;
}

