コード例 #1
0
ファイル: Input.cpp プロジェクト: 456z/gosu
 void pollJoystick(SDL_Joystick *joystick, GamepadBuffer& gamepad)
 {
     int axes = SDL_JoystickNumAxes(joystick),
         hats = SDL_JoystickNumHats(joystick),
         buttons = std::min<int>(gpNumPerGamepad - 4, SDL_JoystickNumButtons(joystick));
     
     for (int axis = 0; axis < axes; ++axis) {
         Sint16 value = SDL_JoystickGetAxis(joystick, axis);
         
         if (value < -DEAD_ZONE) {
             if (axis % 2 == 0)
                 gamepad[gpLeft - gpRangeBegin] = true;
             else
                 gamepad[gpUp - gpRangeBegin] = true;
         }
         else if (value > +DEAD_ZONE) {
             if (axis % 2 == 0)
                 gamepad[gpRight - gpRangeBegin] = true;
             else
                 gamepad[gpDown - gpRangeBegin] = true;
         }
     }
     
     for (int hat = 0; hat < hats; ++hat) {
         Uint8 value = SDL_JoystickGetHat(joystick, hat);
         
         if (value & SDL_HAT_LEFT)
             gamepad[gpLeft - gpRangeBegin] = true;
         if (value & SDL_HAT_RIGHT)
             gamepad[gpRight - gpRangeBegin] = true;
         if (value & SDL_HAT_UP)
             gamepad[gpUp - gpRangeBegin] = true;
         if (value & SDL_HAT_DOWN)
             gamepad[gpDown - gpRangeBegin] = true;
     }
     
     for (int button = 0; button < buttons; ++button) {
         if (SDL_JoystickGetButton(joystick, button)) {
             gamepad[gpButton0 + button - gpRangeBegin] = true;
         }
     }
 }
コード例 #2
0
ファイル: i_sdlinput.cpp プロジェクト: davidsgalbraith/odamex
//
// ISDL12JoystickInputDevice::ISDL12JoystickInputDevice
//
ISDL12JoystickInputDevice::ISDL12JoystickInputDevice(int id) :
	mActive(false), mJoystickId(id), mJoystick(NULL),
	mNumHats(0), mHatStates(NULL)
{
	assert(SDL_WasInit(SDL_INIT_JOYSTICK));
	assert(mJoystickId >= 0 && mJoystickId < SDL_NumJoysticks());

	mJoystick = SDL_JoystickOpen(mJoystickId);
	if (mJoystick == NULL)
		return;

	mNumHats = SDL_JoystickNumHats(mJoystick);
	mHatStates = new int[mNumHats];

	// This turns on automatic event polling for joysticks so that the state
	// of each button and axis doesn't need to be manually queried each tick. -- Hyper_Eye
	SDL_JoystickEventState(SDL_ENABLE);
	
	resume();
}
コード例 #3
0
ファイル: CIrrDeviceSDL.cpp プロジェクト: AwkwardDev/pseuwow
//! Activate any joysticks, and generate events for them.
bool CIrrDeviceSDL::activateJoysticks(core::array<SJoystickInfo> & joystickInfo)
{
#if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_)
	joystickInfo.clear();

	// we can name up to 256 different joysticks
	const int numJoysticks = core::min_(SDL_NumJoysticks(), 256);
	Joysticks.reallocate(numJoysticks);
	joystickInfo.reallocate(numJoysticks);

	int joystick = 0;
	for (; joystick<numJoysticks; ++joystick)
	{
		Joysticks.push_back(SDL_JoystickOpen(joystick));
		SJoystickInfo info;

		info.Joystick = joystick;
		info.Axes = SDL_JoystickNumAxes(Joysticks[joystick]);
		info.Buttons = SDL_JoystickNumButtons(Joysticks[joystick]);
		info.Name = SDL_JoystickName(joystick);
		info.PovHat = (SDL_JoystickNumHats(Joysticks[joystick]) > 0)
						? SJoystickInfo::POV_HAT_PRESENT : SJoystickInfo::POV_HAT_ABSENT;

		joystickInfo.push_back(info);
	}

	for(joystick = 0; joystick < (int)joystickInfo.size(); ++joystick)
	{
		char logString[256];
		(void)sprintf(logString, "Found joystick %d, %d axes, %d buttons '%s'",
		 joystick, joystickInfo[joystick].Axes,
   joystickInfo[joystick].Buttons, joystickInfo[joystick].Name.c_str());
		os::Printer::log(logString, ELL_INFORMATION);
	}

	return true;

#endif // _IRR_COMPILE_WITH_JOYSTICK_EVENTS_

	return false;
}
コード例 #4
0
void							ESInputPlatform::Initialize				(ESInput::InputDeviceList& aDevices, ESInput::InputDeviceList& aSubDevices, uint32_t aESKeyIndex[14])
{
	for(int i = 0; i != SDL_NumJoysticks(); i ++)
	{
		Joysticks.push_back(SDL_JoystickOpen(i));

		aDevices.push_back(ESInput::InputDevice());

		for(int j = 0; j != SDL_JoystickNumAxes(Joysticks[i]); j ++)
		{
			aDevices[i].push_back(ESInput_Button(FetchAxisLow, i, j, 0, vaprint("Joy %d Axis %d Low", i, j)));
			aDevices[i].push_back(ESInput_Button(FetchAxisHigh, i, j, 0, vaprint("Joy %d Axis %d High", i, j)));
		}

		for(int j = 0; j != SDL_JoystickNumHats(Joysticks[i]); j ++)
		{
			aDevices[i].push_back(ESInput_Button(FetchHat, i, j, SDL_HAT_UP, vaprint("Joy %d Hat %d Up", i, j)));
			aDevices[i].push_back(ESInput_Button(FetchHat, i, j, SDL_HAT_DOWN, vaprint("Joy %d Hat %d Down", i, j)));
			aDevices[i].push_back(ESInput_Button(FetchHat, i, j, SDL_HAT_LEFT, vaprint("Joy %d Hat %d Left", i, j)));
			aDevices[i].push_back(ESInput_Button(FetchHat, i, j, SDL_HAT_RIGHT, vaprint("Joy %d Hat %d Right", i, j)));
		}

		for(int j = 0; j != SDL_JoystickNumButtons(Joysticks[i]); j ++)
		{
			aDevices[i].push_back(ESInput_Button(FetchButton, i, j, 0, vaprint("Joy %d Button %d", i, j)));
		}
	}

	//Add a keyboard subdevice
	aSubDevices.push_back(ESInput::InputDevice());

	int numkeys;
	SDL_GetKeyState(&numkeys);
	for(int j = 0; j != numkeys; j ++)
	{
		aSubDevices[0].push_back(ESInput_Button(FetchKey, j, 0, 0, vaprint("KEY %s", SDL_GetKeyName((SDLKey)j))));
	}

	//Load ES Keys
	SDLInputConfig::Load(aESKeyIndex);
}
コード例 #5
0
bool SCA_Joystick::CreateJoystickDevice(void)
{
#ifndef WITH_SDL
	m_isinit = true;
	m_axismax = m_buttonmax = m_hatmax = 0;
	return false;
#else /* WITH_SDL */
	if (m_isinit == false) {
		if (m_joyindex>=m_joynum) {
			// don't print a message, because this is done anyway
			//echo("Joystick-Error: " << SDL_NumJoysticks() << " avaiable joystick(s)");
			
			// Need this so python args can return empty lists
			m_axismax = m_buttonmax = m_hatmax = 0;
			return false;
		}

		m_private->m_joystick = SDL_JoystickOpen(m_joyindex);
		SDL_JoystickEventState(SDL_ENABLE);
		m_isinit = true;
		
		echo("Joystick " << m_joyindex << " initialized");
		
		/* must run after being initialized */
		m_axismax =		SDL_JoystickNumAxes(m_private->m_joystick);
		m_buttonmax =	SDL_JoystickNumButtons(m_private->m_joystick);
		m_hatmax =		SDL_JoystickNumHats(m_private->m_joystick);
		
		if (m_axismax > JOYAXIS_MAX) m_axismax= JOYAXIS_MAX;		/* very unlikely */
		else if (m_axismax < 0) m_axismax = 0;
		
		if (m_hatmax > JOYHAT_MAX) m_hatmax= JOYHAT_MAX;			/* very unlikely */
		else if (m_hatmax<0) m_hatmax= 0;
		
		if (m_buttonmax<0) m_buttonmax= 0;
		
	}
	return true;
#endif /* WITH_SDL */
}
コード例 #6
0
ファイル: joystick.c プロジェクト: Anugrahaa/anagrammatic
static PyObject*
joy_get_hat (PyObject* self, PyObject* args)
{
    int joy_id = PyJoystick_AsID (self);
    SDL_Joystick* joy = joystick_stickdata[joy_id];
    int _index, px, py;
    Uint32 value;

    if (!PyArg_ParseTuple (args, "i", &_index)) {
        return NULL;
    }

    JOYSTICK_INIT_CHECK ();
    if (!joy) {
        return RAISE (PyExc_SDLError, "Joystick not initialized");
    }
    if (_index < 0 || _index >= SDL_JoystickNumHats (joy)) {
        return RAISE(PyExc_SDLError, "Invalid joystick hat");
    }

    px = py = 0;
    value = SDL_JoystickGetHat (joy, _index);
#ifdef DEBUG
    /*printf("SDL_JoystickGetHat value:%d:\n", value);*/
#endif
    if (value & SDL_HAT_UP) {
        py = 1;
    }
    else if (value & SDL_HAT_DOWN) {
        py = -1;
    }
    if (value & SDL_HAT_RIGHT) {
        px = 1;
    }
    else if (value & SDL_HAT_LEFT) {
        px = -1;
    }

    return Py_BuildValue ("(ii)", px, py);
}
コード例 #7
0
ファイル: id_in.cpp プロジェクト: Rinnegatamante/vitaWolfen
///////////////////////////////////////////////////////////////////////////
//
//	IN_Startup() - Starts up the Input Mgr
//
///////////////////////////////////////////////////////////////////////////
void
IN_Startup(void)
{
	if (IN_Started)
		return;

    IN_ClearKeysDown();

    if(param_joystickindex >= 0 && param_joystickindex < SDL_NumJoysticks())
    {
        Joystick = SDL_JoystickOpen(param_joystickindex);
        if(Joystick)
        {
            JoyNumButtons = SDL_JoystickNumButtons(Joystick);
            if(JoyNumButtons > 32) JoyNumButtons = 32;      // only up to 32 buttons are supported
            JoyNumHats = SDL_JoystickNumHats(Joystick);
            if(param_joystickhat < -1 || param_joystickhat >= JoyNumHats)
                Quit("The joystickhat param must be between 0 and %i!", JoyNumHats - 1);
        }
    }

    SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);

    if(fullscreen || forcegrabmouse)
    {
        GrabInput = true;
        SDL_WM_GrabInput(SDL_GRAB_ON);
    }

    // I didn't find a way to ask libSDL whether a mouse is present, yet...
#if defined(GP2X)
    MousePresent = false;
#elif defined(_arch_dreamcast)
    MousePresent = DC_MousePresent();
#else
    MousePresent = true;
#endif

    IN_Started = true;
}
コード例 #8
0
ファイル: Joystick.cpp プロジェクト: amichaelt/pentagram
void InitJoystick()
{
	int i, buttons, axes, balls, hats;
	int joys = SDL_NumJoysticks();

	for (i = 0; i < joys; ++i)
	{
		if (i >= JOY_LAST)
		{
			perr << "Additional joysticks detected. Cannot initialize more than "
				<< JOY_LAST << "." << std::endl;
			break;
		}

		joy[i] = 0;

		if(! SDL_JoystickOpened(i))
		{
			joy[i] = SDL_JoystickOpen(i);
			if (joy[i])
			{
				buttons = SDL_JoystickNumButtons(joy[i]);
				axes = SDL_JoystickNumAxes(joy[i]);
				balls = SDL_JoystickNumBalls(joy[i]);
				hats = SDL_JoystickNumHats(joy[i]);

				pout << "Initialized joystick " << i + 1 << "." << std::endl;
				pout << "\tButtons: " << buttons << std::endl;
				pout << "\tAxes: " << axes << std::endl;
				pout << "\tBalls: " << balls << std::endl;
				pout << "\tHats: " << hats << std::endl;
			}
			else
			{
				perr << "Error while initializing joystick " << i + 1 << "."
					<< std::endl;
			}
		}
	}
}
コード例 #9
0
ファイル: gtk_control.cpp プロジェクト: snes9xgit/snes9x
JoyDevice::JoyDevice (unsigned int device_num)
{
    enabled = false;
    axis = NULL;
    filedes = NULL;
    mode = JOY_MODE_INDIVIDUAL;

    if ((int) device_num >= SDL_NumJoysticks ())
        return;

    filedes = SDL_JoystickOpen (device_num);

    if (!filedes)
        return;

    enabled = true;

    num_axes = SDL_JoystickNumAxes (filedes);
    num_hats = SDL_JoystickNumHats (filedes);
    axis = (int *) malloc (sizeof (int) * num_axes);
    hat  = (int *) malloc (sizeof (int) * num_hats);
    calibration = (Calibration *) malloc (sizeof (Calibration) * num_axes);

    for (int i = 0; i < num_axes; i++)
    {
        calibration[i].min = -32767;
        calibration[i].max = 32767;
        calibration[i].center = 0;
    }

    printf ("Joystick %d, %s:\n  %d axes, %d buttons, %d hats\n",
            device_num + 1,
            SDL_JoystickName (filedes),
            SDL_JoystickNumButtons (filedes),
            num_axes,
            num_hats);

    memset (axis, 0, sizeof (int) * num_axes);
}
コード例 #10
0
// initializes SDL joystick system and loads assignments for joysticks found
void init_joysticks( void )
{
	if (ignore_joystick)
		return;
	
	if (SDL_InitSubSystem(SDL_INIT_JOYSTICK))
	{
		fprintf(stderr, "warning: failed to initialize joystick system: %s\n", SDL_GetError());
		ignore_joystick = true;
		return;
	}
	
	SDL_JoystickEventState(SDL_IGNORE);
	
	joysticks = SDL_NumJoysticks();
	joystick = malloc(joysticks * sizeof(*joystick));
	
	for (int j = 0; j < joysticks; j++)
	{
		memset(&joystick[j], 0, sizeof(*joystick));
		
		joystick[j].handle = SDL_JoystickOpen(j);
		if (joystick[j].handle != NULL)
		{
			printf("joystick detected: %s ", SDL_JoystickName(j));
			printf("(%d axes, %d buttons, %d hats)\n", 
			       SDL_JoystickNumAxes(joystick[j].handle),
			       SDL_JoystickNumButtons(joystick[j].handle),
			       SDL_JoystickNumHats(joystick[j].handle));
			
			if (!load_joystick_assignments(j))
				reset_joystick_assignments(j);
		}
	}
	
	if (joysticks == 0)
		printf("no joysticks detected\n");
}
コード例 #11
0
static boolean IsValidAxis(int axis)
{
    int num_axes;

    if (axis < 0)
    {
        return true;
    }

    if (IS_BUTTON_AXIS(axis))
    {
        return true;
    }

    if (IS_HAT_AXIS(axis))
    {
        return HAT_AXIS_HAT(axis) < SDL_JoystickNumHats(joystick);
    }

    num_axes = SDL_JoystickNumAxes(joystick);

    return axis < num_axes;
}
コード例 #12
0
ファイル: gamepad.cpp プロジェクト: arturo182/BattleTanks
bool Gamepad::otworz(){
	this->urzadzenie = SDL_JoystickOpen(0);
	if(this->urzadzenie == 0)
		return false;

	this->iloscPrzyciskow = SDL_JoystickNumButtons(this->urzadzenie);
	this->iloscNawigatorow = SDL_JoystickNumHats(this->urzadzenie);
	this->iloscDzojstikow = SDL_JoystickNumAxes(this->urzadzenie);

	this->przyciskiPolozenie = new bool[this->iloscPrzyciskow];
	this->przyciskiWcisniete = new bool[this->iloscPrzyciskow];
	this->nawigatoryPolozenie = new int[this->iloscNawigatorow];
	this->nawigatoryWcisniete = new int[this->iloscNawigatorow];
	this->dzojstiki = new short int[this->iloscDzojstikow];

	for(int i = 0; i < this->iloscPrzyciskow; i++)
		this->przyciskiPolozenie[i] = this->przyciskiWcisniete[i] = false;

	for(int i = 0; i < this->iloscNawigatorow; i++)
		this->nawigatoryPolozenie[i] = this->nawigatoryWcisniete[i] = 0;

	return true;
}
コード例 #13
0
bool up() {
    if(!preferences::use_joystick()) {
        return false;
    }

    foreach(SDL_Joystick* j, joysticks) {
        Sint16  y = SDL_JoystickGetAxis(j, 1);
        if (y != 0 && y < 0) {
            return true;
        }

        const int nhats = SDL_JoystickNumHats(j);
        for(int n = 0; n != nhats; ++n) {
            const Uint8 state = SDL_JoystickGetHat(j, n);
            switch(state) {
            case SDL_HAT_UP:
            case SDL_HAT_RIGHTUP:
            case SDL_HAT_LEFTUP:
                return true;
            }
        }

    }
コード例 #14
0
ファイル: event.c プロジェクト: yoyofr/iNEOGEO
bool init_event(void) {
	int i;
    //	printf("sizeof joymap=%d nb_joy=%d\n",sizeof(JOYMAP),conf.nb_joy);
	jmap=calloc(sizeof(JOYMAP),1);
    
#ifdef WII
	conf.nb_joy = 4;
#else	
	conf.nb_joy = SDL_NumJoysticks();
#endif
	if( conf.nb_joy>0) {
		if (conf.joy!=NULL) free(conf.joy);
		conf.joy=calloc(sizeof(SDL_Joystick*),conf.nb_joy);
		
		SDL_JoystickEventState(SDL_ENABLE);
		
		jmap->jbutton=calloc(conf.nb_joy,sizeof(struct BUT_MAP*));
		jmap->jaxe=   calloc(conf.nb_joy,sizeof(struct BUT_MAPJAXIS*));
		jmap->jhat=   calloc(conf.nb_joy,sizeof(struct BUT_MAP*));
		
        
		/* Open all the available joystick */
		for (i=0;i<conf.nb_joy;i++) {
			conf.joy[i]=SDL_JoystickOpen(i);
            /*			printf("joy \"%s\", axe:%d, button:%d\n",
             SDL_JoystickName(i),
             SDL_JoystickNumAxes(conf.joy[i])+ (SDL_JoystickNumHats(conf.joy[i]) * 2),
             SDL_JoystickNumButtons(conf.joy[i]));*/
			jmap->jbutton[i]=calloc(SDL_JoystickNumButtons(conf.joy[i]),sizeof(struct BUT_MAP));
			jmap->jaxe[i]=calloc(SDL_JoystickNumAxes(conf.joy[i]),sizeof(struct BUT_MAPJAXIS));
			jmap->jhat[i]=calloc(SDL_JoystickNumHats(conf.joy[i]),sizeof(struct BUT_MAP));
		}
	}
	create_joymap_from_string(1,CF_STR(cf_get_item_by_name("p1control")));
	create_joymap_from_string(2,CF_STR(cf_get_item_by_name("p2control")));
	return true;
}
コード例 #15
0
ファイル: joystick.c プロジェクト: RetroAsh/chocolate-doom
static int FindUncenteredHat(int *axis_invert)
{
    SDL_Joystick *joystick;
    int i, hatval;

    joystick = all_joysticks[joystick_index];

    for (i = 0; i < SDL_JoystickNumHats(joystick); ++i)
    {
        hatval = SDL_JoystickGetHat(joystick, i);

        switch (hatval)
        {
            case SDL_HAT_LEFT:
            case SDL_HAT_RIGHT:
                *axis_invert = hatval != SDL_HAT_LEFT;
                return CREATE_HAT_AXIS(i, HAT_AXIS_HORIZONTAL);

            case SDL_HAT_UP:
            case SDL_HAT_DOWN:
                *axis_invert = hatval != SDL_HAT_UP;
                return CREATE_HAT_AXIS(i, HAT_AXIS_VERTICAL);

            // If the hat is centered, or is not pointing in a
            // definite direction, then ignore it. We don't accept
            // the hat being pointed to the upper-left for example,
            // because it's ambiguous.
            case SDL_HAT_CENTERED:
            default:
                break;
        }
    }

    // None found.
    return -1;
}
コード例 #16
0
ファイル: joystick.c プロジェクト: xquiet/sdlbasic
//joy									: return joystick boolean coordinate
int joy(int index)
{
    int ret,tmp;
    if (index>=SDL_NumJoysticks())return -1;
    SDL_JoystickUpdate();
    ret=0;
    if (SDLjoy[index] && SDL_JoystickNumAxes(SDLjoy[index])>=2 ){
	tmp= SDL_JoystickGetAxis(SDLjoy[index],0);
	if (tmp<0)
	    ret+=1;
	if (tmp>0)
	    ret+=2;
	tmp= SDL_JoystickGetAxis(SDLjoy[index],1);
	if (tmp<0)
	    ret+=4;
	if (tmp>0)
	    ret+=8;
    }
    if (SDLjoy[index] && SDL_JoystickNumHats(SDLjoy[index])>0 ){
	ret+=SDL_JoystickGetHat(SDLjoy[index],0);
    }
    if (autotimer()!=0)return -1;
    return ret;
}
コード例 #17
0
ファイル: sdl_input.c プロジェクト: raedwulf/etlegacy
static void IN_JoyMove(void)
{
	unsigned int axes  = 0;
	unsigned int hats  = 0;
	int          total = 0;
	int          i     = 0;

	if (!stick)
	{
		return;
	}

	SDL_JoystickUpdate();

	// update the ball state.
	total = SDL_JoystickNumBalls(stick);
	if (total > 0)
	{
		int balldx = 0;
		int balldy = 0;
		int dx;
		int dy;

		for (i = 0; i < total; i++)
		{
			dx = 0;
			dy = 0;

			SDL_JoystickGetBall(stick, i, &dx, &dy);
			balldx += dx;
			balldy += dy;
		}
		if (balldx || balldy)
		{
			// !!! FIXME: is this good for stick balls, or just mice?
			// Scale like the mouse input...
			if (abs(balldx) > 1)
			{
				balldx *= 2;
			}
			if (abs(balldy) > 1)
			{
				balldy *= 2;
			}
			Com_QueueEvent(0, SE_MOUSE, balldx, balldy, 0, NULL);
		}
	}

	// now query the stick buttons...
	total = SDL_JoystickNumButtons(stick);
	if (total > 0)
	{
		if (total > ARRAY_LEN(stick_state.buttons))
		{
			total = ARRAY_LEN(stick_state.buttons);
		}
		for (i = 0; i < total; i++)
		{
			qboolean pressed = (SDL_JoystickGetButton(stick, i) != 0);

			if (pressed != stick_state.buttons[i])
			{
				Com_QueueEvent(0, SE_KEY, K_JOY1 + i, pressed, 0, NULL);
				stick_state.buttons[i] = pressed;
			}
		}
	}

	// look at the hats...
	total = SDL_JoystickNumHats(stick);
	if (total > 0)
	{
		if (total > 4)
		{
			total = 4;
		}
		for (i = 0; i < total; i++)
		{
			((Uint8 *)&hats)[i] = SDL_JoystickGetHat(stick, i);
		}
	}

	// update hat state
	if (hats != stick_state.oldhats)
	{
		for (i = 0; i < 4; i++)
		{
			if (((Uint8 *)&hats)[i] != ((Uint8 *)&stick_state.oldhats)[i])
			{
				// release event
				switch (((Uint8 *)&stick_state.oldhats)[i])
				{
				case SDL_HAT_UP:
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 0], qfalse, 0, NULL);
					break;
				case SDL_HAT_RIGHT:
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 1], qfalse, 0, NULL);
					break;
				case SDL_HAT_DOWN:
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 2], qfalse, 0, NULL);
					break;
				case SDL_HAT_LEFT:
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 3], qfalse, 0, NULL);
					break;
				case SDL_HAT_RIGHTUP:
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 0], qfalse, 0, NULL);
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 1], qfalse, 0, NULL);
					break;
				case SDL_HAT_RIGHTDOWN:
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 2], qfalse, 0, NULL);
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 1], qfalse, 0, NULL);
					break;
				case SDL_HAT_LEFTUP:
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 0], qfalse, 0, NULL);
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 3], qfalse, 0, NULL);
					break;
				case SDL_HAT_LEFTDOWN:
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 2], qfalse, 0, NULL);
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 3], qfalse, 0, NULL);
					break;
				default:
					break;
				}
				// press event
				switch (((Uint8 *)&hats)[i])
				{
				case SDL_HAT_UP:
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 0], qtrue, 0, NULL);
					break;
				case SDL_HAT_RIGHT:
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 1], qtrue, 0, NULL);
					break;
				case SDL_HAT_DOWN:
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 2], qtrue, 0, NULL);
					break;
				case SDL_HAT_LEFT:
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 3], qtrue, 0, NULL);
					break;
				case SDL_HAT_RIGHTUP:
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 0], qtrue, 0, NULL);
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 1], qtrue, 0, NULL);
					break;
				case SDL_HAT_RIGHTDOWN:
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 2], qtrue, 0, NULL);
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 1], qtrue, 0, NULL);
					break;
				case SDL_HAT_LEFTUP:
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 0], qtrue, 0, NULL);
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 3], qtrue, 0, NULL);
					break;
				case SDL_HAT_LEFTDOWN:
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 2], qtrue, 0, NULL);
					Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 3], qtrue, 0, NULL);
					break;
				default:
					break;
				}
			}
		}
	}

	// save hat state
	stick_state.oldhats = hats;

	// finally, look at the axes...
	total = SDL_JoystickNumAxes(stick);
	if (total > 0)
	{
		if (total > 16)
		{
			total = 16;
		}
		for (i = 0; i < total; i++)
		{
			Sint16 axis = SDL_JoystickGetAxis(stick, i);

			if (in_joystickUseAnalog->integer)
			{
				float f = ((float) abs(axis)) / 32767.0f;

				if (f < in_joystickThreshold->value)
				{
					axis = 0;
				}

				if (axis != stick_state.oldaaxes[i])
				{
					Com_QueueEvent(0, SE_JOYSTICK_AXIS, i, axis, 0, NULL);
					stick_state.oldaaxes[i] = axis;
				}
			}
			else
			{
				float f = ((float) axis) / 32767.0f;

				if (f < -in_joystickThreshold->value)
				{
					axes |= (1 << (i * 2));
				}
				else if (f > in_joystickThreshold->value)
				{
					axes |= (1 << ((i * 2) + 1));
				}
			}
		}
	}

	// Time to update axes state based on old vs. new.
	if (axes != stick_state.oldaxes)
	{
		for (i = 0; i < 16; i++)
		{
			if ((axes & (1 << i)) && !(stick_state.oldaxes & (1 << i)))
			{
				Com_QueueEvent(0, SE_KEY, joy_keys[i], qtrue, 0, NULL);
			}

			if (!(axes & (1 << i)) && (stick_state.oldaxes & (1 << i)))
			{
				Com_QueueEvent(0, SE_KEY, joy_keys[i], qfalse, 0, NULL);
			}
		}
	}

	// Save for future generations.
	stick_state.oldaxes = axes;
}
コード例 #18
0
ファイル: sdl_input.c プロジェクト: raedwulf/etlegacy
static void IN_InitJoystick(void)
{
	int  i          = 0;
	int  total      = 0;
	char buf[16384] = "";

	if (stick != NULL)
	{
		SDL_JoystickClose(stick);
	}

	stick = NULL;
	memset(&stick_state, '\0', sizeof(stick_state));

	if (!SDL_WasInit(SDL_INIT_JOYSTICK))
	{
		Com_Printf("Initializing joystick devices\n");
		if (SDL_Init(SDL_INIT_JOYSTICK) < 0)
		{
			Com_Printf("SDL_Init(SDL_INIT_JOYSTICK) failed: %s\n", SDL_GetError());
			return;
		}
		Com_Printf("...joysticks initialized\n");
	}

	total = SDL_NumJoysticks();
	Com_Printf("...available joysticks: %d\n", total);

	// Print list and build cvar to allow ui to select joystick.
	for (i = 0; i < total; i++)
	{
		Q_strcat(buf, sizeof(buf), SDL_JoystickNameForIndex(i));
		Q_strcat(buf, sizeof(buf), "\n");
	}

	Cvar_Get("in_availableJoysticks", buf, CVAR_ROM);

	if (!in_joystick->integer)
	{
		Com_Printf("...no active joystick set\n");
		SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
		return;
	}

	in_joystickNo = Cvar_Get("in_joystickNo", "0", CVAR_ARCHIVE);
	if (in_joystickNo->integer < 0 || in_joystickNo->integer >= total)
	{
		Cvar_Set("in_joystickNo", "0");
	}

	in_joystickUseAnalog = Cvar_Get("in_joystickUseAnalog", "0", CVAR_ARCHIVE);

	stick = SDL_JoystickOpen(in_joystickNo->integer);

	if (stick == NULL)
	{
		Com_Printf("No joystick opened.\n");
		return;
	}

	Com_DPrintf("Joystick %d opened\n", in_joystickNo->integer);
	Com_DPrintf("Name:       %s\n", SDL_JoystickNameForIndex(in_joystickNo->integer));
	Com_DPrintf("Axes:       %d\n", SDL_JoystickNumAxes(stick));
	Com_DPrintf("Hats:       %d\n", SDL_JoystickNumHats(stick));
	Com_DPrintf("Buttons:    %d\n", SDL_JoystickNumButtons(stick));
	Com_DPrintf("Balls:      %d\n", SDL_JoystickNumBalls(stick));
	Com_DPrintf("Use Analog: %s\n", in_joystickUseAnalog->integer ? "Yes" : "No");

	SDL_JoystickEventState(SDL_QUERY);
}
コード例 #19
0
int
main(int argc, char *argv[])
{

    SDL_Window *window;         /* main window */
	SDL_Renderer *renderer;
    Uint32 startFrame;          /* time frame began to process */
    Uint32 endFrame;            /* time frame ended processing */
    Uint32 delay;               /* time to pause waiting to draw next frame */
    int done;                   /* should we clean up and exit? */

    /* initialize SDL */
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
        fatalError("Could not initialize SDL");
    }

    /* create main window and renderer */
//    int bbp = SDL_VideoModeOK(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_FULLSCREEN);
    window = SDL_CreateWindow(NULL, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT,
                                SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN |
                                SDL_WINDOW_BORDERLESS);
    renderer = SDL_CreateRenderer(window, 0, 0);

    /* print out some info about joysticks and try to open accelerometer for use */
    printf("There are %d joysticks available\n", SDL_NumJoysticks());
    printf("Default joystick (index 0) is %s\n", SDL_JoystickName(0));
    accelerometer = SDL_JoystickOpen(0);
    if (accelerometer == NULL) {
        fatalError("Could not open joystick (accelerometer)");
    }
    printf("joystick number of axis = %d\n",
           SDL_JoystickNumAxes(accelerometer));
    printf("joystick number of hats = %d\n",
           SDL_JoystickNumHats(accelerometer));
    printf("joystick number of balls = %d\n",
           SDL_JoystickNumBalls(accelerometer));
    printf("joystick number of buttons = %d\n",
           SDL_JoystickNumButtons(accelerometer));

    /* load graphics */
    initializeTextures(renderer);

    /* setup ship */
    shipData.x = (SCREEN_WIDTH - shipData.rect.w) / 2;
    shipData.y = (SCREEN_HEIGHT - shipData.rect.h) / 2;
    shipData.vx = 0.0f;
    shipData.vy = 0.0f;

    done = 0;
    /* enter main loop */
    while (!done) {
        startFrame = SDL_GetTicks();
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                done = 1;
            }
        }
        render(renderer);
        endFrame = SDL_GetTicks();

        /* figure out how much time we have left, and then sleep */
        delay = MILLESECONDS_PER_FRAME - (endFrame - startFrame);
        if (delay < 0) {
            delay = 0;
        } else if (delay > MILLESECONDS_PER_FRAME) {
            delay = MILLESECONDS_PER_FRAME;
        }
        SDL_Delay(delay);
    }

    /* delete textures */
    SDL_DestroyTexture(ship);
    SDL_DestroyTexture(space);

    /* shutdown SDL */
    SDL_Quit();

    return 0;

}
コード例 #20
0
ファイル: input.c プロジェクト: DrItanium/yquake2
/*
 * Initializes the backend
 */
void
IN_Init(void)
{
	Com_Printf("------- input initialization -------\n");

	mouse_x = mouse_y = 0;

#if SDL_VERSION_ATLEAST(2, 0, 0)
	joystick_yaw = joystick_pitch = joystick_forwardmove = joystick_sidemove = 0;
#endif

	exponential_speedup = Cvar_Get("exponential_speedup", "0", CVAR_ARCHIVE);
	freelook = Cvar_Get("freelook", "1", 0);
	in_grab = Cvar_Get("in_grab", "2", CVAR_ARCHIVE);
	lookstrafe = Cvar_Get("lookstrafe", "0", 0);
	m_filter = Cvar_Get("m_filter", "0", CVAR_ARCHIVE);
	m_up = Cvar_Get("m_up", "1", 0);
	m_forward = Cvar_Get("m_forward", "1", 0);
	m_pitch = Cvar_Get("m_pitch", "0.022", 0);
	m_side = Cvar_Get("m_side", "0.8", 0);
	m_yaw = Cvar_Get("m_yaw", "0.022", 0);
	sensitivity = Cvar_Get("sensitivity", "3", 0);

#if SDL_VERSION_ATLEAST(2, 0, 0)
	joy_haptic_magnitude = Cvar_Get("joy_haptic_magnitude", "0.0", CVAR_ARCHIVE);

	joy_yawsensitivity = Cvar_Get("joy_yawsensitivity", "1.0", CVAR_ARCHIVE);
	joy_pitchsensitivity = Cvar_Get("joy_pitchsensitivity", "1.0", CVAR_ARCHIVE);
	joy_forwardsensitivity = Cvar_Get("joy_forwardsensitivity", "1.0", CVAR_ARCHIVE);
	joy_sidesensitivity = Cvar_Get("joy_sidesensitivity", "1.0", CVAR_ARCHIVE);
	joy_upsensitivity = Cvar_Get("joy_upsensitivity", "1.0", CVAR_ARCHIVE);

	joy_axis_leftx = Cvar_Get("joy_axis_leftx", "sidemove", CVAR_ARCHIVE);
	joy_axis_lefty = Cvar_Get("joy_axis_lefty", "forwardmove", CVAR_ARCHIVE);
	joy_axis_rightx = Cvar_Get("joy_axis_rightx", "yaw", CVAR_ARCHIVE);
	joy_axis_righty = Cvar_Get("joy_axis_righty", "pitch", CVAR_ARCHIVE);
	joy_axis_triggerleft = Cvar_Get("joy_axis_triggerleft", "triggerleft", CVAR_ARCHIVE);
	joy_axis_triggerright = Cvar_Get("joy_axis_triggerright", "triggerright", CVAR_ARCHIVE);

	joy_axis_leftx_threshold = Cvar_Get("joy_axis_leftx_threshold", "0.15", CVAR_ARCHIVE);
	joy_axis_lefty_threshold = Cvar_Get("joy_axis_lefty_threshold", "0.15", CVAR_ARCHIVE);
	joy_axis_rightx_threshold = Cvar_Get("joy_axis_rightx_threshold", "0.15", CVAR_ARCHIVE);
	joy_axis_righty_threshold = Cvar_Get("joy_axis_righty_threshold", "0.15", CVAR_ARCHIVE);
	joy_axis_triggerleft_threshold = Cvar_Get("joy_axis_triggerleft_threshold", "0.15", CVAR_ARCHIVE);
	joy_axis_triggerright_threshold = Cvar_Get("joy_axis_triggerright_threshold", "0.15", CVAR_ARCHIVE);
#endif

	vid_fullscreen = Cvar_Get("vid_fullscreen", "0", CVAR_ARCHIVE);
	windowed_mouse = Cvar_Get("windowed_mouse", "1", CVAR_USERINFO | CVAR_ARCHIVE);

	Cmd_AddCommand("+mlook", IN_MLookDown);
	Cmd_AddCommand("-mlook", IN_MLookUp);

#if SDL_VERSION_ATLEAST(2, 0, 0)
	SDL_StartTextInput();
#else
	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
#endif

#if SDL_VERSION_ATLEAST(2, 0, 0)
	/* joystik init */
	if (!SDL_WasInit(SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC))
	{
		if (SDL_Init(SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC) == -1)
		{
			Com_Printf ("Couldn't init SDL joystick: %s.\n", SDL_GetError ());
		} else {
			Com_Printf ("%i joysticks were found.\n", SDL_NumJoysticks());
			if (SDL_NumJoysticks() > 0) {
				int i;
				for (i=0; i<SDL_NumJoysticks(); i ++) {
					joystick = SDL_JoystickOpen(i);
					Com_Printf ("The name of the joystick is '%s'\n", SDL_JoystickName(joystick));
					Com_Printf ("Number of Axes: %d\n", SDL_JoystickNumAxes(joystick));
					Com_Printf ("Number of Buttons: %d\n", SDL_JoystickNumButtons(joystick));
					Com_Printf ("Number of Balls: %d\n", SDL_JoystickNumBalls(joystick));
					Com_Printf ("Number of Hats: %d\n", SDL_JoystickNumHats(joystick));

					joystick_haptic = SDL_HapticOpenFromJoystick(joystick);
					if (joystick_haptic == NULL)
						Com_Printf ("Most likely joystick isn't haptic\n");
					else
						IN_Haptic_Effects_Info();

					if(SDL_IsGameController(i))
					{
						SDL_GameControllerButtonBind backBind;
						controller = SDL_GameControllerOpen(i);
						Com_Printf ("Controller settings: %s\n", SDL_GameControllerMapping(controller));
						Com_Printf ("Controller axis: \n");
						Com_Printf (" * leftx = %s\n", joy_axis_leftx->string);
						Com_Printf (" * lefty = %s\n", joy_axis_lefty->string);
						Com_Printf (" * rightx = %s\n", joy_axis_rightx->string);
						Com_Printf (" * righty = %s\n", joy_axis_righty->string);
						Com_Printf (" * triggerleft = %s\n", joy_axis_triggerleft->string);
						Com_Printf (" * triggerright = %s\n", joy_axis_triggerright->string);

						Com_Printf ("Controller thresholds: \n");
						Com_Printf (" * leftx = %f\n", joy_axis_leftx_threshold->value);
						Com_Printf (" * lefty = %f\n", joy_axis_lefty_threshold->value);
						Com_Printf (" * rightx = %f\n", joy_axis_rightx_threshold->value);
						Com_Printf (" * righty = %f\n", joy_axis_righty_threshold->value);
						Com_Printf (" * triggerleft = %f\n", joy_axis_triggerleft_threshold->value);
						Com_Printf (" * triggerright = %f\n", joy_axis_triggerright_threshold->value);

						backBind = SDL_GameControllerGetBindForButton(controller, SDL_CONTROLLER_BUTTON_BACK);

						if (backBind.bindType == SDL_CONTROLLER_BINDTYPE_BUTTON) {
							back_button_id = backBind.value.button;
							Com_Printf ("\nBack button JOY%d will be unbindable.\n", back_button_id+1);
						}
						break;
					}
					else
					{
						char joystick_guid[256] = {0};
						SDL_JoystickGUID guid;
						guid = SDL_JoystickGetDeviceGUID(i);
						SDL_JoystickGetGUIDString(guid, joystick_guid, 255);
						Com_Printf ("For use joystic as game contoller please set SDL_GAMECONTROLLERCONFIG:\n");
						Com_Printf ("e.g.: SDL_GAMECONTROLLERCONFIG='%s,%s,leftx:a0,lefty:a1,rightx:a2,righty:a3,back:b1,...\n", joystick_guid, SDL_JoystickName(joystick));
					}
				}
			}
			else
			{
				joystick_haptic = SDL_HapticOpenFromMouse();
				if (joystick_haptic == NULL)
					Com_Printf ("Most likely mouse isn't haptic\n");
				else
					IN_Haptic_Effects_Info();
			}
		}
	}
#endif

	Com_Printf("------------------------------------\n\n");
}
コード例 #21
0
ファイル: sdlstuff.c プロジェクト: rdebath/sgt
int main(int argc, char **argv)
{
    SDL_Surface *screen;
    SDL_AudioSpec audio_wanted;
    int frame;
    int evfd;
    int x, y;

    evfd = open("/dev/ps2event", O_RDONLY);
    if (evfd < 0) { perror("/dev/ps2event: open"); return 1; }
    ioctl(evfd, PS2IOC_ENABLEEVENT, PS2EV_VSYNC);

    dx = get_dx();
    dy = get_dy();
    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK);
    atexit(cleanup);

    if (argc > 1 && !strcmp(argv[1], "-j")) {
	int i;
	SDL_Event event;
	SDL_Joystick *joystick;

	printf("%d joysticks were found.\n\n", SDL_NumJoysticks() );
	printf("The names of the joysticks are:\n");
	for (i=0; i < SDL_NumJoysticks(); i++) {
	    printf("    %s\n", SDL_JoystickName(i));
	}

	joystick = SDL_JoystickOpen(0);
	printf("Joystick 0 has %d axes\n", SDL_JoystickNumAxes(joystick));
	printf("Joystick 0 has %d buttons\n", SDL_JoystickNumButtons(joystick));
	printf("Joystick 0 has %d balls\n", SDL_JoystickNumBalls(joystick));
	printf("Joystick 0 has %d hats\n", SDL_JoystickNumHats(joystick));

	while(SDL_WaitEvent(&event)) {
	    switch(event.type) {
	      case SDL_JOYAXISMOTION:
		printf("Axis %d %d\n", event.jaxis.axis, event.jaxis.value);
		break;
	      case SDL_JOYBUTTONDOWN:
		printf("Button %d down\n", event.jbutton.button);
		break;
	      case SDL_JOYBUTTONUP:
		printf("Button %d up\n", event.jbutton.button);
		break;
	      case SDL_KEYDOWN:
		goto done;
		break;
	    }
	}
	done:

	return 0;
    }

    /*
     * Set the audio device up.
     */
    audio_wanted.freq = 22050;
    audio_wanted.format = AUDIO_S8;
    audio_wanted.channels = 1;    /* 1 = mono, 2 = stereo */
    audio_wanted.samples = 1024;  /* Good low-latency value for callback */
    audio_wanted.callback = fill_audio;
    audio_wanted.userdata = NULL;
    if ( SDL_OpenAudio(&audio_wanted, NULL) < 0 ) {
        fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
        return 1;
    }

    /*
     * Set the video mode up.
     */
    screen = SDL_SetVideoMode(SCR_WIDTH*XMULT, SCR_HEIGHT*YMULT,
			      8, SDL_SWSURFACE);
    if (!screen) {
	printf("SDL screen initialisation error: %s\n", SDL_GetError());
	return 1;
    }
    SDL_ShowCursor(SDL_DISABLE);

    if (SDL_MUSTLOCK(screen))
	SDL_LockSurface(screen);
    for (x = 0; x < SCR_WIDTH*XMULT; x++) {
	for (y = 0; y < SCR_HEIGHT*YMULT; y++) {
	    putpixel(screen, x, y,
		     SDL_MapRGB(screen->format, (x*10)&255,
				(y*10)&255, ((x+y+frame)*10)&255));
	}
    }
    if (SDL_MUSTLOCK(screen))
	SDL_UnlockSurface(screen);

    SDL_PauseAudio(0);

    for (frame = 1; frame < 256; frame++) {
	SDL_Rect r1 = { 0, 0, SCR_WIDTH*XMULT-1, SCR_HEIGHT*YMULT };
	SDL_Rect r2 = { 1, 0, SCR_WIDTH*XMULT-1, SCR_HEIGHT*YMULT };
	
	if (SDL_MUSTLOCK(screen))
	    SDL_LockSurface(screen);
//	for (x = 0; x < SCR_WIDTH*XMULT; x++) {
	    for (y = 0; y < SCR_HEIGHT*YMULT; y++) {
		memmove(screen->pixels + y * screen->pitch,
			screen->pixels + y * screen->pitch + screen->format->BytesPerPixel,
			(SCR_WIDTH*XMULT-1) * screen->format->BytesPerPixel);
		putpixel(screen, SCR_WIDTH*XMULT-1, y, 0);
		//putpixel(screen, x, y, (x==SCR_WIDTH*XMULT-1 ? 0 :
		//			getpixel(screen, x+1, y)));
	    }
//	}
	if (SDL_MUSTLOCK(screen))
	    SDL_UnlockSurface(screen);
	//SDL_UpdateRect(screen, frame*2, 0, 2, SCR_HEIGHT*YMULT);
	SDL_Flip(screen);
	{
	    long long t = bigclock();
	    ioctl(evfd, PS2IOC_WAITEVENT, PS2EV_VSYNC);
	    sparetime += bigclock() - t;
	}
    }

    return 0;
}
コード例 #22
0
ファイル: joystick.cpp プロジェクト: DeejStar/xoreos
int Joystick::getHatCount() const {
	if (!_sdlJoy)
		return 0;

	return SDL_JoystickNumHats(_sdlJoy);
}
コード例 #23
0
ファイル: sdl2-jstest.c プロジェクト: marxjohnson/sdl-jstest
void test_joystick(int joy_idx)
{
  SDL_Joystick* joy = SDL_JoystickOpen(joy_idx);
  if (!joy)
  {
    fprintf(stderr, "Unable to open joystick %d\n", joy_idx);
  }
  else
  {
    initscr();

    //cbreak();
    //noecho();
    //nonl();
    curs_set(0);

    int num_axes    = SDL_JoystickNumAxes(joy);
    int num_buttons = SDL_JoystickNumButtons(joy);
    int num_hats    = SDL_JoystickNumHats(joy);
    int num_balls   = SDL_JoystickNumBalls(joy);

    Sint16* axes    = calloc(num_axes,    sizeof(Sint16));
    Uint8*  buttons = calloc(num_buttons, sizeof(Uint8));
    Uint8*  hats    = calloc(num_hats,    sizeof(Uint8));
    Uint8*  balls   = calloc(num_balls,   2*sizeof(Sint16));

    int quit = 0;
    SDL_Event event;
    while(!quit)
    {
      SDL_Delay(10);

      bool something_new = false;
      while (SDL_PollEvent(&event)) {
        something_new = true;
        switch(event.type)
        {
          case SDL_JOYAXISMOTION:
            assert(event.jaxis.axis < num_axes);
            axes[event.jaxis.axis] = event.jaxis.value;
            break;

          case SDL_JOYBUTTONDOWN:
          case SDL_JOYBUTTONUP:
            assert(event.jbutton.button < num_buttons);
            buttons[event.jbutton.button] = event.jbutton.state;
            break;

          case SDL_JOYHATMOTION:
            assert(event.jhat.hat < num_hats);
            hats[event.jhat.hat] = event.jhat.value;
            break;

          case SDL_JOYBALLMOTION:
            assert(event.jball.ball < num_balls);
            balls[2*event.jball.ball + 0] = event.jball.xrel;
            balls[2*event.jball.ball + 1] = event.jball.yrel;
            break;

          case SDL_QUIT:
            quit = 1;
            printf("Recieved interrupt, exiting\n");
            break;

          default:
            fprintf(stderr, "Error: Unhandled event type: %d\n", event.type);
        }
      }

      if (something_new)
      {
        //clear();
        move(0,0);

        printw("Joystick Name:   '%s'\n", SDL_JoystickName(joy));
        printw("Joystick Number: %d\n", joy_idx);
        printw("\n");

        printw("Axes %2d:\n", num_axes);
        for(int i = 0; i < num_axes; ++i)
        {
          int len = COLS - 20;
          printw("  %2d: %6d  ", i, axes[i]);
          print_bar((axes[i] + 32767) * (len-1) / 65534, len);
          addch('\n');
        }
        printw("\n");

        printw("Buttons %2d:\n", num_buttons);
        for(int i = 0; i < num_buttons; ++i)
        {
          printw("  %2d: %d  %s\n", i, buttons[i], buttons[i] ? "[#]":"[ ]");
        }
        printw("\n");

        printw("Hats %2d:\n", num_hats);
        for(int i = 0; i < num_hats; ++i)
        {
          printw("  %2d: value: %d\n", i, hats[i]);
          printw("  +-----+  up:    %c\n"
                 "  |%c %c %c|  down:  %c\n"
                 "  |%c %c %c|  left:  %c\n"
                 "  |%c %c %c|  right: %c\n"
                 "  +-----+\n",

                 (hats[i] & SDL_HAT_UP)?'1':'0',

                 ((hats[i] & SDL_HAT_UP) && (hats[i] & SDL_HAT_LEFT)) ? 'O' : ' ',
                 ((hats[i] & SDL_HAT_UP) && !(hats[i] & (SDL_HAT_LEFT | SDL_HAT_RIGHT))) ? 'O' : ' ',
                 ((hats[i] & SDL_HAT_UP) && (hats[i] & SDL_HAT_RIGHT)) ? 'O' : ' ',

                 (hats[i] & SDL_HAT_DOWN)?'1':'0',

                 (!(hats[i] & (SDL_HAT_UP | SDL_HAT_DOWN)) && (hats[i] & SDL_HAT_LEFT)) ? 'O' : ' ',
                 (!(hats[i] & (SDL_HAT_UP | SDL_HAT_DOWN)) && !(hats[i] & (SDL_HAT_LEFT | SDL_HAT_RIGHT))) ? 'O' : ' ',
                 (!(hats[i] & (SDL_HAT_UP | SDL_HAT_DOWN)) && (hats[i] & SDL_HAT_RIGHT)) ? 'O' : ' ',

                 (hats[i] & SDL_HAT_LEFT)?'1':'0',

                 ((hats[i] & SDL_HAT_DOWN) && (hats[i] & SDL_HAT_LEFT)) ? 'O' : ' ',
                 ((hats[i] & SDL_HAT_DOWN) && !(hats[i] & (SDL_HAT_LEFT | SDL_HAT_RIGHT))) ? 'O' : ' ',
                 ((hats[i] & SDL_HAT_DOWN) && (hats[i] & SDL_HAT_RIGHT)) ? 'O' : ' ',

                 (hats[i] & SDL_HAT_RIGHT)?'1':'0');
        }
        printw("\n");

        printw("Balls %2d: ", num_balls);
        for(int i = 0; i < num_balls; ++i)
        {
          printw("  %2d: %6d %6d\n", i, balls[2*i+0], balls[2*i+0]);
        }
        printw("\n");
        printw("\n");
        printw("Press Ctrl-c to exit\n");

        refresh();
      }
    } // while

    free(balls);
    free(hats);
    free(buttons);
    free(axes);

    endwin();
  }
}
コード例 #24
0
// captures joystick input for configuring assignments
// returns false if non-joystick input was detected
// TODO: input from joystick other than the one being configured probably should not be ignored
bool detect_joystick_assignment( int j, Joystick_assignment *assignment )
{
	// get initial joystick state to compare against to see if anything was pressed
	
	const int axes = SDL_JoystickNumAxes(joystick[j].handle);
	Sint16 *axis = malloc(axes * sizeof(*axis));
	for (int i = 0; i < axes; i++)
		axis[i] = SDL_JoystickGetAxis(joystick[j].handle, i);
	
	const int buttons = SDL_JoystickNumButtons(joystick[j].handle);
	Uint8 *button = malloc(buttons * sizeof(*button));
	for (int i = 0; i < buttons; i++)
		button[i] = SDL_JoystickGetButton(joystick[j].handle, i);
	
	const int hats = SDL_JoystickNumHats(joystick[j].handle);
	Uint8 *hat = malloc(hats * sizeof(*hat));
	for (int i = 0; i < hats; i++)
		hat[i] = SDL_JoystickGetHat(joystick[j].handle, i);
	
	bool detected = false;
	
	do
	{
		setjasondelay(1);
		
		SDL_JoystickUpdate();
		
		for (int i = 0; i < axes; ++i)
		{
			Sint16 temp = SDL_JoystickGetAxis(joystick[j].handle, i);
			
			if (abs(temp - axis[i]) > joystick_analog_max * 2 / 3)
			{
				assignment->type = AXIS;
				assignment->num = i;
				assignment->negative_axis = temp < axis[i];
				detected = true;
				break;
			}
		}
		
		for (int i = 0; i < buttons; ++i)
		{
			Uint8 new_button = SDL_JoystickGetButton(joystick[j].handle, i),
			      changed = button[i] ^ new_button;
			
			if (!changed)
				continue;
			
			if (new_button == 0) // button was released
			{
				button[i] = new_button;
			}
			else                 // button was pressed
			{
				assignment->type = BUTTON;
				assignment->num = i;
				detected = true;
				break;
			}
		}
		
		for (int i = 0; i < hats; ++i)
		{
			Uint8 new_hat = SDL_JoystickGetHat(joystick[j].handle, i),
			      changed = hat[i] ^ new_hat;
			
			if (!changed)
				continue;
			
			if ((new_hat & changed) == SDL_HAT_CENTERED) // hat was centered
			{
				hat[i] = new_hat;
			}
			else
			{
				assignment->type = HAT;
				assignment->num = i;
				assignment->x_axis = changed & (SDL_HAT_LEFT | SDL_HAT_RIGHT);
				assignment->negative_axis = changed & (SDL_HAT_LEFT | SDL_HAT_UP);
				detected = true;
			}
		}
		
		service_SDL_events(true);
		JE_showVGA();
		
		wait_delay();
	}
	while (!detected && !newkey && !newmouse);
	
	free(axis);
	free(button);
	free(hat);
	
	return detected;
}
コード例 #25
0
ファイル: SDL.cpp プロジェクト: Zombiebest/Dolphin
Joystick::Joystick(SDL_Joystick* const joystick, const int sdl_index, const unsigned int index)
	: m_joystick(joystick)
	, m_sdl_index(sdl_index)
	, m_index(index)
{
	// really bad HACKS:
	// to not use SDL for an XInput device
	// too many people on the forums pick the SDL device and ask:
	// "why don't my 360 gamepad triggers/rumble work correctly"
#ifdef _WIN32
	// checking the name is probably good (and hacky) enough
	// but i'll double check with the num of buttons/axes
	std::string lcasename = GetName();
	std::transform(lcasename.begin(), lcasename.end(), lcasename.begin(), tolower);

	if ((std::string::npos != lcasename.find("xbox 360"))
		&& (10 == SDL_JoystickNumButtons(joystick))
		&& (5 == SDL_JoystickNumAxes(joystick))
		&& (1 == SDL_JoystickNumHats(joystick))
		&& (0 == SDL_JoystickNumBalls(joystick))
		)
	{
		// this device won't be used
		return;
	}
#endif

	// get buttons
	for (u8 i = 0; i != SDL_JoystickNumButtons(m_joystick); ++i)
		AddInput(new Button(i, m_joystick));
	
	// get hats
	for (u8 i = 0; i != SDL_JoystickNumHats(m_joystick); ++i)
	{
		// each hat gets 4 input instances associated with it, (up down left right)
		for (u8 d = 0; d != 4; ++d)
			AddInput(new Hat(i, m_joystick, d));
	}

	// get axes
	for (u8 i = 0; i != SDL_JoystickNumAxes(m_joystick); ++i)
	{
		// each axis gets a negative and a positive input instance associated with it
		AddAnalogInputs(new Axis(i, m_joystick, -32768),
			new Axis(i, m_joystick, 32767));
	}

#ifdef USE_SDL_HAPTIC
	// try to get supported ff effects
	m_haptic = SDL_HapticOpenFromJoystick( m_joystick );
	if (m_haptic)
	{
		//SDL_HapticSetGain( m_haptic, 1000 );
		//SDL_HapticSetAutocenter( m_haptic, 0 );

		const unsigned int supported_effects = SDL_HapticQuery( m_haptic );

		// constant effect
		if (supported_effects & SDL_HAPTIC_CONSTANT)
		{
			m_state_out.push_back(EffectIDState());
			AddOutput(new ConstantEffect(m_state_out.back()));
		}

		// ramp effect
		if (supported_effects & SDL_HAPTIC_RAMP)
		{
			m_state_out.push_back(EffectIDState());
			AddOutput(new RampEffect(m_state_out.back()));
		}

		// sine effect
		if (supported_effects & SDL_HAPTIC_SINE)
		{
			m_state_out.push_back(EffectIDState());
			AddOutput(new SineEffect(m_state_out.back()));
		}

		// square effect
		if (supported_effects & SDL_HAPTIC_SQUARE)
		{
			m_state_out.push_back(EffectIDState());
			AddOutput(new SquareEffect(m_state_out.back()));
		}

		// triangle effect
		if (supported_effects & SDL_HAPTIC_TRIANGLE)
		{
			m_state_out.push_back(EffectIDState());
			AddOutput(new TriangleEffect(m_state_out.back()));
		}
	}
#endif

}
コード例 #26
0
int main( int argc, char *argv[]) {

// this was a quick test of InetOpenURL
#if 0
	HINTERNET hnet = InternetOpen( "Game", INTERNET_OPEN_TYPE_PRECONFIG, 
									NULL, NULL, 0 );
	HINTERNET hfile = InternetOpenUrl( hnet, "http://www.yahoo.com", 
										NULL, 0, 
										INTERNET_FLAG_DONT_CACHE, 0);
	char buff[5000];
	unsigned long nread;
	InternetReadFile( hfile, buff, 5000, &nread );
	buff[nread] = 0;
	printf( buff );
#endif

	if ( SDL_Init(SDL_INIT_NOPARACHUTE | SDL_INIT_AUDIO|SDL_INIT_VIDEO |SDL_INIT_JOYSTICK) < 0 ) {
        fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
        exit(1);
    }

	if( SDL_SetVideoMode( 800, 600, 16, SDL_OPENGL /*| SDL_FULLSCREEN */ ) == 0 ) {
		fprintf(stderr,	"Unable to set video mode: %s\n", SDL_GetError());
        exit(1);
	}

	SDL_WM_SetCaption( "The Halloween Machine", NULL );

	// Init SDL_Mixer
	if (Mix_OpenAudio( 22050, AUDIO_S16, 2,  4096 )) {
		fprintf(stderr,	"Unable to open audio\n");
        exit(1);
	}

	// Initialize Joysticks/Gamepads
	printf("%d Controllers found.\n", SDL_NumJoysticks() );
	for (int i=0; i < SDL_NumJoysticks(); i++) {
		printf( "Controller %d: %s\n", i, SDL_JoystickName(i) );
	}
	gamepad.name = "No gamepad detected.";
	gamepad.sdlinfo = NULL;
	gamepad.stick = vec2f(0.0, 0.0 );
	gamepad.stick2 = vec2f(0.0, 0.0 );

	// Only use the first controller
	if (SDL_NumJoysticks() > 0 ) {
		gamepad.sdlinfo = SDL_JoystickOpen(0);
	}

	// init highscores
	readHighScores();	

	if (gamepad.sdlinfo) {
		gamepad.name = strdup( SDL_JoystickName(0) );
		printf( "Gamepad: Number of axes: %d\n", SDL_JoystickNumAxes(gamepad.sdlinfo) );
		printf( "Gamepad: Number of buttons: %d\n", SDL_JoystickNumButtons(gamepad.sdlinfo) );
		printf( "Gamepad: Number of balls: %d\n", SDL_JoystickNumBalls(gamepad.sdlinfo) );
		printf( "Gamepad: Number of hats: %d\n", SDL_JoystickNumHats(gamepad.sdlinfo) );
	}

	

	// initialize DevIL
	ilInit();
	ilutRenderer( ILUT_OPENGL );

	// Setup glgameFont
	
	// Load the font image
	ilGenImages( 1, &ilFontId );
	ilBindImage( ilFontId );		
	
	if (!ilLoadImage( "gamedata/magic.png" )) {
		printf("Loading font image failed\n");
	}
	
	// Make a GL texture for it
	glFontTexId = ilutGLBindTexImage();

	// Create a font by passing in an opengl texture id
	fntFontId = gfCreateFont( glFontTexId );

	// A .finfo file contains the metrics for a font. These
	// are generated by the Fontpack utility.
	gfLoadFontMetrics( fntFontId, "gamedata/magic.finfo");

	printf("font has %d chars\n", gfGetFontMetric( fntFontId, GF_FONT_NUMCHARS ) );
	gfEnableFont( fntFontId, 25 );		

	sfx[0] = Mix_LoadWAV("gamedata/whiit.wav");
	sfx[1] = Mix_LoadWAV("gamedata/didge.wav");
	sfx[2] = Mix_LoadWAV("gamedata/sfx_boom.wav");
	sfx[3] = Mix_LoadWAV("gamedata/harp.wav");
	sfx[4] = Mix_LoadWAV("gamedata/secret.wav");

	music_title = Mix_LoadMUS( "gamedata/AutumnLeft.ogg" );
	music_gameover = Mix_LoadMUS( "gamedata/YouDiedLoser.ogg" );
	music_ingame = Mix_LoadMUS( "gamedata/ingame.ogg" );

	if (!music_title) {
		printf("Error loading music %s\n", Mix_GetError() );
	} else {
		printf("Music loaded\n");
	}
	Mix_PlayMusic( music_title, -1 );

	
	// Start up the game
	g_game = new GameState();
	g_game->init();

	g_game->loadLevels( "gamedata/levels.txt" );

	g_view = new ViewSimple2D( g_game );
	g_game->setView( g_view );	

	//////////////////////
	// Event Loop
	//////////////////////
	while (1) {		
    SDL_Event event;

    /* Grab all the events off the queue. */
    while( SDL_PollEvent( &event ) ) {
		
        switch( event.type ) {
        case SDL_KEYDOWN:

			// are we reading highscore??
			if (ndxGetName >=0 ) {
				char buff[10];
				if ( ((event.key.keysym.sym >= SDLK_a) && (event.key.keysym.sym <= SDLK_z)) ||					 
					 ((event.key.keysym.sym >= SDLK_0) && (event.key.keysym.sym <= SDLK_9))) {
					sprintf( buff, "%c", (char)event.key.keysym.sym );

					if (event.key.keysym.mod & (KMOD_LSHIFT|KMOD_RSHIFT)) {
						buff[0] = toupper(buff[0]);
					}

					if (!strcmp(g_highScoreTable[ndxGetName].m_name.c_str(), HISCORE_PROMPT)) {
						g_highScoreTable[ndxGetName].m_name = "";
					}

					g_highScoreTable[ndxGetName].m_name.append( buff);

				} else if ( (event.key.keysym.sym==SDLK_BACKSPACE) ) {
					if (g_highScoreTable[ndxGetName].m_name.length()){ 
						g_highScoreTable[ndxGetName].m_name.erase( 
											g_highScoreTable[ndxGetName].m_name.end()-1 );
					}
				} else if ( (event.key.keysym.sym==SDLK_RETURN) ||
					      (event.key.keysym.sym==SDLK_ESCAPE) ) {

					if (!g_highScoreTable[ndxGetName].m_name.length()) {
						g_highScoreTable[ndxGetName].m_name = "Anonymous";
					}

					ndxGetName = -1;


					writeHighScores();
				}

				break;
			} 

            switch( event.key.keysym.sym ) {

				case SDLK_ESCAPE:				
					if ( (g_state==STATE_TITLE) &&
						(g_menuState == MENU_MAINMENU)) {
						do_quit();
					} else {
						backToTitleScreen();
					}
					break;

				case SDLK_a:
					g_view->toggleAnim();
					break;

				case SDLK_p:
					paused = !paused;
					break;

// Cheat codes.. enable for testing
#if 0
				case SDLK_z:
					if (g_state==STATE_GAMEOVER) {
						ndxGetName = 3;
						break;
					}
	
					

				case SDLK_1:
					g_game->dbgNextPumpkin( PUMPKIN );
					break;
				case SDLK_2:
					g_game->dbgNextPumpkin( PUMPKIN_ORANGE );
					break;
				case SDLK_3:
					g_game->dbgNextPumpkin( PUMPKIN_YELLOW );
					break;
				case SDLK_4:
					g_game->dbgNextPumpkin( PUMPKIN_RED );
					break;
				case SDLK_5:
					g_game->dbgNextPumpkin( SKULL );
					break;
				case SDLK_6:
					g_game->dbgNextPumpkin( FISH_HEAD );
					break;
				case SDLK_7:
					g_game->dbgNextPumpkin( BLACKBIRD );
					break;

				case SDLK_8:
					g_game->dbgClearQueue();
					break;
#endif


				case SDLK_s:
					ilutGLScreenie();
					break; 

				case SDLK_d:
					bDrawGamepad = !bDrawGamepad;
					break;

				case SDLK_m:					

					if (!musicOn) {
						printf("Playing\n");
						if (g_state==STATE_TITLE) {
							Mix_PlayMusic( music_title, -1 );
						} else if (g_state==STATE_PLAYING) {
							Mix_PlayMusic( music_ingame, -1 );
						} else if (g_state==STATE_GAMEOVER) {
							// easter egg.. kindof.. you get to hear the
							// game over music again. woo.
							Mix_PlayMusic( music_gameover, 0 );
						}
						musicOn = 1;
					} else {
						printf("Halting\n");
						Mix_HaltMusic();
						musicOn = 0;
					}


				case SDLK_LEFT:
					g_view->nextStation();
					break;
				case SDLK_RIGHT:
					g_view->prevStation();
					break;

				case SDLK_SPACE:
				case SDLK_RETURN:
					if (g_state == STATE_PLAYING) {
						doActivateStation();
					} else {
						doStartButton();
					}
					
					break;

				case SDLK_UP:
					if (g_state==STATE_PLAYING) {
						//g_view->activateStation();
						doActivateStation();
					} else if (g_state==STATE_TITLE ) {
						prevMenuItem();						
					}
					break;

				case SDLK_DOWN:
					if (g_state==STATE_TITLE ) {
						nextMenuItem();						
					}
					break;

				default:
					break;
				}
			break;

		

		case SDL_JOYAXISMOTION:  /* Handle Joystick Motion */
			if ( ( event.jaxis.value < -3200 ) || (event.jaxis.value > 3200 ) ) 
			{				

				switch(event.jaxis.axis) {				
				case 0:
					gamepad.stick[0] = (float)(event.jaxis.value) / 32768.0f;
					break;
				case 1:
					gamepad.stick[1] = (float)(event.jaxis.value) / 32768.0f;
					break;
				case 2:
					gamepad.throttle = (float)(event.jaxis.value) / 32768.0f;
					break;
				case 3:
					gamepad.stick2[0] = (float)(event.jaxis.value) / 32768.0f;
					break;
				case 4:															
					gamepad.stick2[1] = (float)(event.jaxis.value) / 32768.0f;					
					break;						
				}				
				
			} else {
				// prevent jitter near the center positions
				switch(event.jaxis.axis) {
				case 0:
					gamepad.stick[0] = 0.0;
					break;
				case 1:
					gamepad.stick[1] = 0.0;
					break;
				case 2:
					gamepad.throttle = 0.0;
					break;
				case 3:
					gamepad.stick2[0] = 0.0;
					break;
				case 4:
					gamepad.stick2[1] = 0.0;
					break;				
				}
			}
			break;

		case SDL_JOYBUTTONDOWN:  /* Handle Joystick Button Presses */
			gamepad.button[event.jbutton.button] = true;
			
			switch (event.jbutton.button) {
			case 0:				
				//g_view->activateStation();
				if (g_state==STATE_PLAYING) {
					doActivateStation();
				} else {
					doStartButton();
				}
				break;
			//case 1:
			//	sfx_chan[1] = Mix_PlayChannel(-1, sfx[1], 0);
			//	break;
			//case 2:
			//	sfx_chan[2] = Mix_PlayChannel(-1, sfx[2], 0);
			//	break;

			case 8: // start button 
				doStartButton();				
				break;

			}
			break;

		case SDL_JOYBUTTONUP:  /* Handle Joystick Button Release */
			gamepad.button[event.jbutton.button] = false;			
			break;

		case SDL_JOYHATMOTION:  /* Handle Hat Motion */			
			gamepad.hat = event.jhat.value;			

			if (g_state==STATE_PLAYING) {
	
				if (gamepad.hat & SDL_HAT_LEFT) {
				
					g_view->nextStation();
				}

				if (gamepad.hat & SDL_HAT_RIGHT) {
					g_view->prevStation();
				}				
			} else {
				if (gamepad.hat & SDL_HAT_UP) {
				
					prevMenuItem();
				}

				if (gamepad.hat & SDL_HAT_DOWN) {
					nextMenuItem();
				}
			}

			break;
			case SDL_QUIT:
				/* Handle quit requests (like Ctrl-c). */
				if ( (g_state==STATE_TITLE) &&
					(g_menuState == MENU_MAINMENU)) {
					do_quit();
				} else {
					backToTitleScreen();
				}
				break;
			}	
		}
		redraw();
	}
	return 0;
} 
コード例 #27
0
ファイル: sdlsystem.cpp プロジェクト: slagusev/lobster
string SDLInit(const char *title, int2 &screensize, bool fullscreen)
{
    //SDL_SetMainReady();
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER /* | SDL_INIT_AUDIO*/) < 0)
    {
        return SDLError("Unable to initialize SDL");
    }

    SDL_SetEventFilter(SDLHandleAppEvents, nullptr);

    DebugLog(-1, "SDL initialized...");

    SDL_LogSetAllPriority(SDL_LOG_PRIORITY_WARN);

    // on demand now
    //extern bool sfxr_init();
    //if (!sfxr_init())
    //   return SDLError("Unable to initialize audio");

    #ifdef PLATFORM_MOBILE
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
    #else
    //certain older Intel HD GPUs and also Nvidia Quadro 1000M don't support 3.1 ? the 1000M is supposed to support 4.2
    //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
    #ifndef WIN32
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
    #endif
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
    #endif

    //SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);      // set this if we're in 2D mode for speed on mobile?
    SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 1);    // because we redraw the screen each frame

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    DebugLog(-1, "SDL about to figure out display mode...");

    #ifdef PLATFORM_MOBILE
    landscape = screensize.x() >= screensize.y();
    int modes = SDL_GetNumDisplayModes(0);
    screensize = int2(0);
    for (int i = 0; i < modes; i++)
    {
        SDL_DisplayMode mode;
        SDL_GetDisplayMode(0, i, &mode);
        //printf("mode: %d %d\n", mode.w, mode.h);
        if (landscape ? mode.w > screensize.x() : mode.h > screensize.y())
        {
            screensize = int2(mode.w, mode.h);
        }
    }

    DebugLog(-1, inttoa(screensize.x()));
    DebugLog(-1, inttoa(screensize.y()));
    DebugLog(-1, "SDL about to create window...");

    _sdl_window = SDL_CreateWindow(title,
                                    0, 0,
                                    screensize.x(), screensize.y(),
                                    SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS);

    DebugLog(-1, _sdl_window ? "SDL window passed..." : "SDL window FAILED...");

    if (landscape) SDL_SetHint("SDL_HINT_ORIENTATIONS", "LandscapeLeft LandscapeRight");

    int ax = 0, ay = 0;
    SDL_GetWindowSize(_sdl_window, &ax, &ay);
    int2 actualscreensize(ax, ay);
    //screenscalefactor = screensize.x / actualscreensize.x;  // should be 2 on retina
    #ifdef __IOS__
        assert(actualscreensize == screensize);
        screensize = actualscreensize;
    #else
        screensize = actualscreensize;  // __ANDROID__
        DebugLog(-1, inttoa(screensize.x()));
        DebugLog(-1, inttoa(screensize.y()));
    #endif
    #else
    _sdl_window = SDL_CreateWindow(title,
                                    SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                    screensize.x(), screensize.y(),
                                    SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE |
                                        (fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0));
    #endif

    if (!_sdl_window)
        return SDLError("Unable to create window");

    DebugLog(-1, "SDL window opened...");


    _sdl_context = SDL_GL_CreateContext(_sdl_window);
    DebugLog(-1, _sdl_context ? "SDL context passed..." : "SDL context FAILED...");
    if (!_sdl_context) return SDLError("Unable to create OpenGL context");

    DebugLog(-1, "SDL OpenGL context created...");

    /*
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
    */

    #ifndef __IOS__
        SDL_GL_SetSwapInterval(1);  // vsync on
    #endif

    SDL_JoystickEventState(SDL_ENABLE);
    SDL_JoystickUpdate();
    for(int i = 0; i < SDL_NumJoysticks(); i++)
    {
        SDL_Joystick *joy;
        if (joy = SDL_JoystickOpen(i))
        {
            DebugLog(-1, "Detected joystick: %s (%d axes, %d buttons, %d balls, %d hats)\n",
                         SDL_JoystickName(joy), SDL_JoystickNumAxes(joy), SDL_JoystickNumButtons(joy),
                         SDL_JoystickNumBalls(joy), SDL_JoystickNumHats(joy));
        };
    };

    starttime = SDL_GetTicks();
    lastmillis = starttime - 16;    // ensure first frame doesn't get a crazy delta

    return "";
}
コード例 #28
0
int
main(int argc, char *argv[])
{
    const char *name;
    int i;
    SDL_Joystick *joystick;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);	

    /* Initialize SDL (Note: video is required to start event loop) */
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
        exit(1);
    }

    /* Print information about the joysticks */
    SDL_Log("There are %d joysticks attached\n", SDL_NumJoysticks());
    for (i = 0; i < SDL_NumJoysticks(); ++i) {
        name = SDL_JoystickNameForIndex(i);
        SDL_Log("Joystick %d: %s\n", i, name ? name : "Unknown Joystick");
        joystick = SDL_JoystickOpen(i);
        if (joystick == NULL) {
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_JoystickOpen(%d) failed: %s\n", i,
                    SDL_GetError());
        } else {
            char guid[64];
            SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick),
                                      guid, sizeof (guid));
            SDL_Log("       axes: %d\n", SDL_JoystickNumAxes(joystick));
            SDL_Log("      balls: %d\n", SDL_JoystickNumBalls(joystick));
            SDL_Log("       hats: %d\n", SDL_JoystickNumHats(joystick));
            SDL_Log("    buttons: %d\n", SDL_JoystickNumButtons(joystick));
            SDL_Log("instance id: %d\n", SDL_JoystickInstanceID(joystick));
            SDL_Log("       guid: %s\n", guid);
            SDL_JoystickClose(joystick);
        }
    }

#ifdef ANDROID
    if (SDL_NumJoysticks() > 0) {
#else
    if (argv[1]) {
#endif
        SDL_bool reportederror = SDL_FALSE;
        SDL_bool keepGoing = SDL_TRUE;
        SDL_Event event;
        int device;
#ifdef ANDROID
        device = 0;
#else
        device = atoi(argv[1]);
#endif
        joystick = SDL_JoystickOpen(device);

        while ( keepGoing ) {
            if (joystick == NULL) {
                if ( !reportederror ) {
                    SDL_Log("Couldn't open joystick %d: %s\n", device, SDL_GetError());
                    keepGoing = SDL_FALSE;
                    reportederror = SDL_TRUE;
                }
            } else {
                reportederror = SDL_FALSE;
                keepGoing = WatchJoystick(joystick);
                SDL_JoystickClose(joystick);
            }

            joystick = NULL;
            if (keepGoing) {
                SDL_Log("Waiting for attach\n");
            }
            while (keepGoing) {
                SDL_WaitEvent(&event);
                if ((event.type == SDL_QUIT) || (event.type == SDL_FINGERDOWN)
                    || (event.type == SDL_MOUSEBUTTONDOWN)) {
                    keepGoing = SDL_FALSE;
                } else if (event.type == SDL_JOYDEVICEADDED) {
                    joystick = SDL_JoystickOpen(device);
                    break;
                }
            }
        }
    }
    else {
        SDL_Log("\n\nUsage: ./controllermap number\nFor example: ./controllermap 0\nOr: ./controllermap 0 >> gamecontrollerdb.txt");
    }
    SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK);

    return 0;
}

#else

int
main(int argc, char *argv[])
{
    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL compiled without Joystick support.\n");
    exit(1);
}
コード例 #29
0
ファイル: sdlfn.c プロジェクト: 8l/bcpl
BCPLWORD sdlfn(BCPLWORD *a, BCPLWORD *g, BCPLWORD *W) {
  char tmpstr[256];

  //printf("sdlfn: fno=%d a1=%d a2=%d a3=%d a4=%d\n",
  //        a[0], a[1], a[2], a[3], a[4]);

  switch(a[0]) {
  default:
    printf("sdlfn: Unknown op: fno=%d a1=%d a2=%d a3=%d a4=%d\n",
            a[0], a[1], a[2], a[3], a[4]);
    return 0;

  case sdl_avail: // Test whether SDL is available
    return -1;    // SDL is available

  case gl_avail:  // Test whether OpenGL is available
#ifdef GLavail
    return -1;    // OpenGL is available
#else
    return  0;    // OpenGL is not available
#endif

  case sdl_init:  // Initialise all SDL features
  { BCPLWORD res = (BCPLWORD) SDL_Init(SDL_INIT_EVERYTHING);
      // Enable Unicode translation of keyboard events.
    SDL_EnableUNICODE(1);
    SDL_JoystickEventState(SDL_ENABLE);
    //printf("sdl_init\n");
    return res;
  }

  case sdl_setvideomode:  // width, height, bbp, flags
  { SDL_Surface *scr;
    //printf("Calling SetVideoMode(%d, %d, %d, %8x)\n", a[1], a[2], a[3], a[4]);
    scr = SDL_SetVideoMode((int)a[1], (int)a[2], (int)a[3], (Uint32)a[4]);
    SDL_Flip(scr);
    return (BCPLWORD) scr;
    //return (BCPLWORD) SDL_SetVideoMode((int)a[1], (int)a[2], (int)a[3], (Uint32)a[4]);
  }

  case sdl_quit:      // Shut down SDL
    printf("sdl_quit\n");
    SDL_Quit();
    return -1;

  case sdl_locksurface: // surf
    // Return 0 on success
    // Return -1 on failure
    return (BCPLWORD) SDL_LockSurface((SDL_Surface*) a[1]);

  case sdl_unlocksurface: // surf
    SDL_UnlockSurface((SDL_Surface*) a[1]);
    return 0;

  case sdl_getsurfaceinfo:
  // surf, surfinfo -> [flag, format, w, h, pitch, pixels, cliprect, refcount]
  { SDL_Surface *surf = (SDL_Surface*)a[1];
    BCPLWORD *info = &W[a[2]];
    info[ 0] = (BCPLWORD) (surf->flags);
    info[ 1] = (BCPLWORD) (surf->format);
    info[ 2] = (BCPLWORD) (surf->w);
    info[ 3] = (BCPLWORD) (surf->h);
    info[ 4] = (BCPLWORD) (surf->pitch);
    info[ 5] = (BCPLWORD) (surf->pixels);
    //info[ 6] = (BCPLWORD) (surf->clip_rect); // fields: x,y, w, h
    info[ 7] = (BCPLWORD) (surf->refcount);
    //printf("getsurfaceinfo: format=%d\n", info[1]);
    return 0;        
  }

  case sdl_getfmtinfo:
  // fmt, pxlinfo -> [palette, bitspp, bytespp, rmask, gmask, rmask, amask,
  //                  rloss, rshift, gloss, gshift, bloss, bshift, aloss, ashift,
  //                  colorkey, alpha]
  { SDL_PixelFormat *fmt = (SDL_PixelFormat*)(a[1]);
    BCPLWORD *info = &(W[a[2]]);
    //printf("getfmtinfo: format=%d\n", (BCPLWORD)fmt);
    info[ 0] = (BCPLWORD) (fmt->palette);
    info[ 1] = (BCPLWORD) (fmt->BitsPerPixel);
    info[ 2] = (BCPLWORD) (fmt->BytesPerPixel);
    info[ 3] = (BCPLWORD) (fmt->Rmask);
    info[ 4] = (BCPLWORD) (fmt->Gmask);
    info[ 5] = (BCPLWORD) (fmt->Bmask);
    info[ 6] = (BCPLWORD) (fmt->Amask);
    info[ 7] = (BCPLWORD) (fmt->Rshift);
    info[ 8] = (BCPLWORD) (fmt->Gshift);
    info[ 9] = (BCPLWORD) (fmt->Bshift);
    info[10] = (BCPLWORD) (fmt->Ashift);
    info[11] = (BCPLWORD) (fmt->Rloss);
    info[12] = (BCPLWORD) (fmt->Gloss);
    info[13] = (BCPLWORD) (fmt->Rloss);
    info[14] = (BCPLWORD) (fmt->Aloss);
    info[15] = (BCPLWORD) (fmt->colorkey);
    info[16] = (BCPLWORD) (fmt->alpha);

    return 0;        
  }

  case sdl_geterror:   // str -- fill str with BCPL string for the latest SDL error
  { char *str = SDL_GetError();
    printf("sdl_geterror: %s\n", str);
    return c2b_str(str, a[1]); // Convert to BCPL string format
  }

  case sdl_updaterect: // surf, left, top, right, bottom
    return 0;     // Not yet available

  case sdl_loadbmp:    // filename of a .bmp image
  { char tmpstr[256];
    b2c_str(a[1], tmpstr);
    return (BCPLWORD) SDL_LoadBMP(tmpstr);
  }

  case sdl_mksurface: //(format, w, h)
  { SDL_PixelFormat *fmt = (SDL_PixelFormat*)(a[1]);
    Uint32 rmask = fmt->Rmask;
    Uint32 gmask = fmt->Gmask;
    Uint32 bmask = fmt->Bmask;
    Uint32 amask = fmt->Amask;
    //printf("rmask=%8x gmask=%8x bmask=%8x amask=%8x\n", rmask, gmask, bmask, amask);
    return (BCPLWORD)SDL_CreateRGBSurface(
                         SDL_SWSURFACE,
                         a[2], a[3], // Width, Height
                         32,     // Not using a palette
                         rmask, gmask, bmask, amask);
  }

  case sdl_blitsurface: // src, srcrect, dest, destrect
    //printf("blitsurface: %d, %d, %d, %d)\n", a[1], a[2], a[3], a[4]);
  { BCPLWORD *p = &W[a[4]];
    SDL_Rect dstrect = {p[0],p[1],p[2],p[3]};
    //printf("x=%d, y=%d, w=%d, h=%d\n", p[0], p[1], p[2], p[3]);
    return (BCPLWORD) SDL_BlitSurface((SDL_Surface*) a[1],
                                      (SDL_Rect*)    0,
                                      (SDL_Surface*) a[3],
                                      &dstrect);
  }

  case sdl_setcolourkey: //(surf, key)
    // If key=-1 unset colour key
    // otherwise set colour key to given value.
    // key must be in the pixel format of the given surface
    //printf("sdl_setcolourkey: %8x\n", a[2]);
    if(a[2]==-1) {
      return (BCPLWORD)SDL_SetColorKey((SDL_Surface*)a[1], 0, (Uint32)a[2]);
    } else {
      return (BCPLWORD)SDL_SetColorKey((SDL_Surface*)a[1], SDL_SRCCOLORKEY, (Uint32)a[2]);
    }

  case sdl_freesurface: // surf
    SDL_FreeSurface((SDL_Surface*)a[1]);
    return 0;

  case sdl_setalpha:    // surf, flags, alpha
    return 0;     // Not yet available

  case sdl_imgload:     // filename -- using the SDL_image library
    return 0;     // Not yet available

  case sdl_delay:       // msecs -- the SDL delay function
    SDL_Delay((int)a[1]);
    return 0;

  case sdl_getticks:    // return msecs since initialisation
    return (BCPLWORD)SDL_GetTicks();

  case sdl_showcursor:  // Show the cursor
    return (BCPLWORD)SDL_ShowCursor(SDL_ENABLE);

  case sdl_hidecursor:  // Hide the cursor
    return (BCPLWORD)SDL_ShowCursor(SDL_DISABLE);

  case sdl_flip:        // surf -- Double buffered update of the screen
    return (BCPLWORD) SDL_Flip((SDL_Surface*)a[1]);

  case sdl_displayformat: // surf -- convert surf to display format
    return 0;     // Not yet available

  case sdl_waitevent:    // (pointer) to [type, args, ... ] to hold details of the next event
                 // return 0 if no events available
    return 0;     // Not yet available

  case sdl_pollevent:    // (pointer) to [type, args, ... ] to hold details of
			 // the next event
    { SDL_Event test_event;
      if (SDL_PollEvent(&test_event))
      { decodeevent(&test_event, &W[a[1]]);
        return -1;
      }
      decodeevent(0, &W[a[1]]);
      return 0;
    }

  case sdl_getmousestate: // pointer to [x, y] returns bit pattern of buttons currently pressed
    return 0;     // Not yet available

  case sdl_loadwav:      // file, spec, buff, len
    return 0;     // Not yet available

  case sdl_freewav:      // buffer
    return 0;     // Not yet available

  case sdl_wm_setcaption:      // surf, string
  { char tmpstr[256];
    b2c_str(a[1], tmpstr);
    SDL_WM_SetCaption(tmpstr, 0);
    return 0;
  }

  case sdl_videoinfo:      // buffer
  { const SDL_VideoInfo* p = SDL_GetVideoInfo();
    BCPLWORD *info = &W[a[1]];
    info[ 0] = (BCPLWORD) ((p->hw_available) |
                           (p->hw_available)<<1 |
                           (p->blit_hw)<<2 |
                           (p->blit_hw_CC)<<3 |
                           (p->blit_hw_A)<<4 |
                           (p->blit_sw)<<5 |
                           (p->blit_sw_CC)<<6 |
                           (p->blit_sw_A)<<7
                          );
    info[ 1] = (BCPLWORD) (p->blit_fill);
    info[ 2] = (BCPLWORD) (p->video_mem);
    info[ 3] = (BCPLWORD) (p->vfmt);
    info[ 4] = (BCPLWORD) (p->vfmt->BitsPerPixel);
    //printf("videoinfo: a[2]=%d %8X %8X %d %d %d\n",
    //          a[2], info[0], info[1], info[2], info[3], info[4]);
 
    return 0;
  }


  case sdl_maprgb:      // format, r, g, b
  { 
    return (BCPLWORD) SDL_MapRGB((SDL_PixelFormat*)(a[1]), a[2], a[3], a[4]); 
  }

  case sdl_drawline:
  { SDL_Surface *surf = (SDL_Surface*)(a[1]);
    //printf("\nDraw Line: %d %d %d %d %d %8x\n", a[1], a[2], a[3], a[4], a[5], a[6]);
    Draw_Line(surf, a[2], a[3], a[4], a[5], a[6]);
    return 0;
  }

  case sdl_drawhline:
  case sdl_drawvline:
  case sdl_drawcircle:
  case sdl_drawrect:
  case sdl_drawpixel:
  case sdl_drawellipse:
  case sdl_drawfillellipse:
  case sdl_drawround:
  case sdl_drawfillround:
    return 0;

  case sdl_drawfillcircle:
  { SDL_Surface *surf = (SDL_Surface*)(a[1]);
    Draw_FillCircle(surf, a[2], a[3], a[4], a[5]);
    return 0;
  }
    //  case sdl_drawfillrect:
    //return  Draw_FillRect((SDL_Surface*)a[1], 500,200, 50,70, 0xF0FF00);

  case sdl_fillrect:
  { SDL_Rect rect = {a[2],a[3],a[4],a[5]};
    //printf("\nfillrect: surface=%d rect=(%d,%d,%d,%d) col=%8x\n",
    //       a[1], a[2], a[3], a[4], a[5], a[6]);
    SDL_FillRect((SDL_Surface*)(a[1]), &rect, a[6]);
    return 0;
  }

  case sdl_fillsurf:
    //printf("\nfillsurf: surface=%d col=%8x\n",
    //        a[1], a[2]);
    SDL_FillRect((SDL_Surface*)(a[1]), 0, a[2]);
    return 0;

// Joystick functions
  case sdl_numjoysticks:
    return SDL_NumJoysticks();

  case sdl_joystickopen:       // 42 (index) => joy
    return (BCPLWORD)SDL_JoystickOpen(a[1]);

  case sdl_joystickclose:      // 43 (joy)
    SDL_JoystickClose((SDL_Joystick *)a[1]);
    return 0;

  case sdl_joystickname:       // 44 (index)
  { const char *name = SDL_JoystickName(a[1]);
    return c2b_str(name, a[1]);
  }

  case sdl_joysticknumaxes:    // 45 (joy)
    return SDL_JoystickNumAxes((SDL_Joystick*)a[1]);

  case sdl_joysticknumbuttons: // 46 (joy)
    return SDL_JoystickNumButtons((SDL_Joystick*)a[1]);

  case sdl_joysticknumballs:   // 47 (joy)
    return SDL_JoystickNumBalls((SDL_Joystick*)a[1]);

  case sdl_joysticknumhats:    // 47 (joy)
    return SDL_JoystickNumHats((SDL_Joystick*)a[1]);

  case sdl_joystickeventstate: //49  sdl_enable=1 or sdl_ignore=0
    return SDL_JoystickEventState(a[1]);

  case sdl_joystickgetbutton: // 55 (joy)
    return SDL_JoystickGetButton((SDL_Joystick*)a[1], a[2]);

  case sdl_joystickgetaxis: // 56 (joy)
    return SDL_JoystickGetAxis((SDL_Joystick*)a[1], a[2]);

  case sdl_joystickgethat: // 58 (joy)
    return SDL_JoystickGetHat((SDL_Joystick*)a[1], a[2]);

  case gl_setvideomode: // 200 (width, height)
  { // Setup minimum bit sizes, a depth buffer and double buffering.
    const SDL_VideoInfo* info = NULL;
    int bpp = 0;
    SDL_Surface *scr;

    info = SDL_GetVideoInfo();
    if(!info) return 0;
    bpp = info->vfmt->BitsPerPixel;
    printf("bpp=%d width=%d height=%d\n", bpp, a[1], a[2]);
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    printf("Calling SDL_SetVideoMode\n");
    scr = SDL_SetVideoMode((int)a[1], (int)a[2], bpp, SDL_OPENGL);
    return (BCPLWORD)scr;
  }

#ifdef GLavail
  case gl_ShadeModel:
    //printf("gl_ShadeModel: a[1]=%d GL_SMOOTH=%d\n", a[1], GL_SMOOTH);
    //glShadeModel((int)a[1]);
    //glShadeModel(GL_SMOOTH);
    return 0;
  case gl_CullFace:
    //printf("gl_CullFace: %d GL_BACK=%d\n", a[1], GL_BACK);
    //glCullFace(a[1]);
    glCullFace(GL_BACK);
    return 0;
  case gl_FrontFace:
    //printf("gl_FrontFace: %d\n", a[1]);
    //printf("   GL_CCW=%d\n", GL_CCW);
    //glFrontFace(a[1]);
    glFrontFace(GL_CCW);
    return 0;
  case gl_Enable:
    //printf("gl_Enable: %d\n", a[1]);
    //printf("   GL_CULLFACE=%d\n", GL_CULL_FACE);
    glEnable(a[1]);
    return 0;
  case gl_ClearColor:
    //printf("gl_ClearColor: %d %d %d %d\n", a[1], a[2], a[3], a[4]);
    glClearColor(a[1]/255.0, a[2]/255.0, a[3]/255.0, a[4]/255.0);
    return 0;
  case gl_ViewPort:
    //printf("gl_Viewport: %d %d %d %d\n", a[1], a[2], a[3], a[4]);
    glViewport(a[1], a[2], a[3], a[4]);
    //glViewport(0, 0, 800, 500);
    return 0;
  case gl_MatrixMode:
    //printf("gl_MatrixMode: %d\n", a[1]);
    //printf("   GL_PROJECTION=%d\n", GL_PROJECTION);
    //printf("   GL_MODELVIEW=%d\n", GL_MODELVIEW);
    glMatrixMode(a[1]);
    return 0;
  case gl_LoadIdentity:
    //printf("gl_LoadIdentity:\n");
    glLoadIdentity();
    return 0;
  case glu_Perspective:
    //printf("gl_Perspective: %d %d %d %d\n", a[1], a[2], a[3], a[4]);
    gluPerspective(((float)a[1])/1000000, ((float)a[2])/1000000,
                   ((float)a[3])/1000, ((float)a[4])/1000);  
    //gluPerspective(60.0, 800.0/500.0, 1.0, 1024.0);
    return 0;
  case gl_Clear:
    //printf("gl_Clear: #x%8X\n", a[1]);
    //printf("   GL_COLOR_BUFFER_BIT=%8X\n", GL_COLOR_BUFFER_BIT);
    //printf("   GL_DEPTH_BUFFER_BIT=%8X\n", GL_DEPTH_BUFFER_BIT);
    glClear(a[1]);
    //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    return 0;
  case gl_Translate:
    //printf("gl_Translate: %d %d %d\n", a[1], a[2], a[3]);
    glTranslatef(a[1]/1000.0, a[2]/1000.0, a[3]/1000.0);
    return 0;
  case gl_Rotate:
    //printf("gl_Rotate: %d %d %d %d\n", a[1], a[2], a[3], a[4]);
    glRotatef(a[1]/1000000.0, a[2]/1000.0, a[3]/1000.0, a[4]/1000.0);
    return 0;
  case gl_Begin:
    //printf("gl_Begin: %d\n", a[1]);
    //printf("   GL_TRIANGLES=%d\n", GL_TRIANGLES);
    glBegin(a[1]);
    return 0;
  case gl_End:
    //printf("gl_End:\n");
    glEnd();
    return 0;
  case gl_Color4v:
    //printf("gl_Color4v: %d\n", a[1]);
    glColor4ub(W[a[1]], W[a[1]+1], W[a[1]+2], W[a[1]+3]);
    return 0;
  case gl_Vertex3v:
    //printf("gl_Vertex3v: %d -> [%d %d %d]\n", a[1], W[a[1]], W[a[1]+1], W[a[1]+2]);
    glVertex3f(W[a[1]]/1000.0, W[a[1]+1]/1000.0, W[a[1]+2]/1000.0);
    return 0;
  case gl_SwapBuffers:
    //printf("gl_SwapBuffers:\n");
    SDL_GL_SwapBuffers();
    return 0;
#endif

// more to come ...

  }
}
コード例 #30
0
static SDL_bool
WatchJoystick(SDL_Joystick * joystick)
{
    SDL_Window *window = NULL;
    SDL_Renderer *screen = NULL;
    SDL_Texture *background, *button, *axis, *marker;
    const char *name = NULL;
    SDL_bool retval = SDL_FALSE;
    SDL_bool done = SDL_FALSE, next=SDL_FALSE;
    SDL_Event event;
    SDL_Rect dst;
    int s, _s;
    Uint8 alpha=200, alpha_step = -1;
    Uint32 alpha_ticks;
    char mapping[4096], temp[4096];
    MappingStep *step;
    MappingStep steps[] = {
        {342, 132,  0.0,  MARKER_BUTTON, "x", -1, -1, -1, -1, ""},
        {387, 167,  0.0,  MARKER_BUTTON, "a", -1, -1, -1, -1, ""},
        {431, 132,  0.0,  MARKER_BUTTON, "b", -1, -1, -1, -1, ""},
        {389, 101,  0.0,  MARKER_BUTTON, "y", -1, -1, -1, -1, ""},
        {174, 132,  0.0,  MARKER_BUTTON, "back", -1, -1, -1, -1, ""},
        {233, 132,  0.0,  MARKER_BUTTON, "guide", -1, -1, -1, -1, ""},
        {289, 132,  0.0,  MARKER_BUTTON, "start", -1, -1, -1, -1, ""},        
        {116, 217,  0.0,  MARKER_BUTTON, "dpleft", -1, -1, -1, -1, ""},
        {154, 249,  0.0,  MARKER_BUTTON, "dpdown", -1, -1, -1, -1, ""},
        {186, 217,  0.0,  MARKER_BUTTON, "dpright", -1, -1, -1, -1, ""},
        {154, 188,  0.0,  MARKER_BUTTON, "dpup", -1, -1, -1, -1, ""},
        {77,  40,   0.0,  MARKER_BUTTON, "leftshoulder", -1, -1, -1, -1, ""},
        {91, 0,    0.0,  MARKER_BUTTON, "lefttrigger", -1, -1, -1, -1, ""},
        {396, 36,   0.0,  MARKER_BUTTON, "rightshoulder", -1, -1, -1, -1, ""},
        {375, 0,    0.0,  MARKER_BUTTON, "righttrigger", -1, -1, -1, -1, ""},
        {75,  154,  0.0,  MARKER_BUTTON, "leftstick", -1, -1, -1, -1, ""},
        {305, 230,  0.0,  MARKER_BUTTON, "rightstick", -1, -1, -1, -1, ""},
        {75,  154,  0.0,  MARKER_AXIS,   "leftx", -1, -1, -1, -1, ""},
        {75,  154,  90.0, MARKER_AXIS,   "lefty", -1, -1, -1, -1, ""},        
        {305, 230,  0.0,  MARKER_AXIS,   "rightx", -1, -1, -1, -1, ""},
        {305, 230,  90.0, MARKER_AXIS,   "righty", -1, -1, -1, -1, ""},
    };

    /* Create a window to display joystick axis position */
    window = SDL_CreateWindow("Game Controller Map", SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH,
                              SCREEN_HEIGHT, 0);
    if (window == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError());
        return SDL_FALSE;
    }

    screen = SDL_CreateRenderer(window, -1, 0);
    if (screen == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError());
        SDL_DestroyWindow(window);
        return SDL_FALSE;
    }
    
    background = LoadTexture(screen, "controllermap.bmp", SDL_FALSE);
    button = LoadTexture(screen, "button.bmp", SDL_TRUE);
    axis = LoadTexture(screen, "axis.bmp", SDL_TRUE);
    SDL_RaiseWindow(window);

    /* scale for platforms that don't give you the window size you asked for. */
    SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT);

    /* Print info about the joystick we are watching */
    name = SDL_JoystickName(joystick);
    SDL_Log("Watching joystick %d: (%s)\n", SDL_JoystickInstanceID(joystick),
           name ? name : "Unknown Joystick");
    SDL_Log("Joystick has %d axes, %d hats, %d balls, and %d buttons\n",
           SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
           SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
    
    SDL_Log("\n\n\
    ====================================================================================\n\
    Press the buttons on your controller when indicated\n\
    (Your controller may look different than the picture)\n\
    If you want to correct a mistake, press backspace or the back button on your device\n\
    To skip a button, press SPACE or click/touch the screen\n\
    To exit, press ESC\n\
    ====================================================================================\n");
    
    /* Initialize mapping with GUID and name */
    SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, SDL_arraysize(temp));
    SDL_snprintf(mapping, SDL_arraysize(mapping), "%s,%s,platform:%s,",
        temp, name ? name : "Unknown Joystick", SDL_GetPlatform());

    /* Loop, getting joystick events! */
    for(s=0; s<SDL_arraysize(steps) && !done;) {
        /* blank screen, set up for drawing this frame. */
        step = &steps[s];
        SDL_strlcpy(step->mapping, mapping, SDL_arraysize(step->mapping));
        step->axis = -1;
        step->button = -1;
        step->hat = -1;
        step->hat_value = -1;
        SDL_SetClipboardText("TESTING TESTING 123");
        
        switch(step->marker) {
            case MARKER_AXIS:
                marker = axis;
                break;
            case MARKER_BUTTON:
                marker = button;
                break;
            default:
                break;
        }
        
        dst.x = step->x;
        dst.y = step->y;
        SDL_QueryTexture(marker, NULL, NULL, &dst.w, &dst.h);
        next=SDL_FALSE;

        SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE);

        while (!done && !next) {
            if (SDL_GetTicks() - alpha_ticks > 5) {
                alpha_ticks = SDL_GetTicks();
                alpha += alpha_step;
                if (alpha == 255) {
                    alpha_step = -1;
                }
                if (alpha < 128) {
                    alpha_step = 1;
                }
            }
            
            SDL_RenderClear(screen);
            SDL_RenderCopy(screen, background, NULL, NULL);
            SDL_SetTextureAlphaMod(marker, alpha);
            SDL_SetTextureColorMod(marker, 10, 255, 21);
            SDL_RenderCopyEx(screen, marker, NULL, &dst, step->angle, NULL, 0);
            SDL_RenderPresent(screen);
            
            if (SDL_PollEvent(&event)) {
                switch (event.type) {
                case SDL_JOYAXISMOTION:
                    if (event.jaxis.value > 20000 || event.jaxis.value < -20000) {
                        for (_s = 0; _s < s; _s++) {
                            if (steps[_s].axis == event.jaxis.axis) {
                                break;
                            }
                        }
                        if (_s == s) {
                            step->axis = event.jaxis.axis;
                            SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
                            SDL_snprintf(temp, SDL_arraysize(temp), ":a%u,", event.jaxis.axis);
                            SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
                            s++;
                            next=SDL_TRUE;
                        }
                    }
                    
                    break;
                case SDL_JOYHATMOTION:
                        if (event.jhat.value == SDL_HAT_CENTERED) {
                            break;  /* ignore centering, we're probably just coming back to the center from the previous item we set. */
                        }
                        for (_s = 0; _s < s; _s++) {
                            if (steps[_s].hat == event.jhat.hat && steps[_s].hat_value == event.jhat.value) {
                                break;
                            }
                        }
                        if (_s == s) {
                            step->hat = event.jhat.hat;
                            step->hat_value = event.jhat.value;
                            SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
                            SDL_snprintf(temp, SDL_arraysize(temp), ":h%u.%u,", event.jhat.hat, event.jhat.value );
                            SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
                            s++;
                            next=SDL_TRUE;
                        }
                    break;
                case SDL_JOYBALLMOTION:
                    break;
                case SDL_JOYBUTTONUP:
                    for (_s = 0; _s < s; _s++) {
                        if (steps[_s].button == event.jbutton.button) {
                            break;
                        }
                    }
                    if (_s == s) {
                        step->button = event.jbutton.button;
                        SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
                        SDL_snprintf(temp, SDL_arraysize(temp), ":b%u,", event.jbutton.button);
                        SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
                        s++;
                        next=SDL_TRUE;
                    }
                    break;
                case SDL_FINGERDOWN:
                case SDL_MOUSEBUTTONDOWN:
                    /* Skip this step */
                    s++;
                    next=SDL_TRUE;
                    break;
                case SDL_KEYDOWN:
                    if (event.key.keysym.sym == SDLK_BACKSPACE || event.key.keysym.sym == SDLK_AC_BACK) {
                        /* Undo! */
                        if (s > 0) {
                            SDL_strlcpy(mapping, step->mapping, SDL_arraysize(step->mapping));
                            s--;
                            next = SDL_TRUE;
                        }
                        break;
                    }
                    if (event.key.keysym.sym == SDLK_SPACE) {
                        /* Skip this step */
                        s++;
                        next=SDL_TRUE;
                        break;
                    }
                    
                    if ((event.key.keysym.sym != SDLK_ESCAPE)) {
                        break;
                    }
                    /* Fall through to signal quit */
                case SDL_QUIT:
                    done = SDL_TRUE;
                    break;
                default:
                    break;
                }
            }
        }

    }

    if (s == SDL_arraysize(steps) ) {
        SDL_Log("Mapping:\n\n%s\n\n", mapping);
        /* Print to stdout as well so the user can cat the output somewhere */
        printf("%s\n", mapping);
    }
    
    while(SDL_PollEvent(&event)) {};
    
    SDL_DestroyRenderer(screen);
    SDL_DestroyWindow(window);
    return retval;
}