Example #1
0
	void refresh_controllers()
	{
		for (s32 i = 0; i < MAX_GAMEPADS; i++)
		{
			if (haptics[i])
			{
				SDL_HapticClose(haptics[i]);
				haptics[i] = nullptr;
			}

			if (controllers[i])
			{
				SDL_GameControllerClose(controllers[i]);
				controllers[i] = nullptr;
			}
		}

		for (s32 i = 0; i < SDL_NumJoysticks(); i++)
		{
			if (SDL_IsGameController(i))
			{
				controllers[i] = SDL_GameControllerOpen(i);
				SDL_Joystick* joystick = SDL_GameControllerGetJoystick(controllers[i]);
				if (SDL_JoystickIsHaptic(joystick))
				{
					haptics[i] = SDL_HapticOpenFromJoystick(joystick);
					if (SDL_HapticRumbleInit(haptics[i])) // failed
					{
						SDL_HapticClose(haptics[i]);
						haptics[i] = nullptr;
					}
				}
			}
		}
	}
Example #2
0
/**
 * @brief Initializes force feedback for the loaded device.
 */
static void joystick_initHaptic (void)
{
#if SDL_VERSION_ATLEAST(1,3,0)
    if (has_haptic && SDL_JoystickIsHaptic(joystick)) {

        /* Close haptic if already open. */
        if (haptic != NULL) {
            SDL_HapticClose(haptic);
            haptic = NULL;
        }

        /* Try to create haptic device. */
        haptic = SDL_HapticOpenFromJoystick(joystick);
        if (haptic == NULL) {
            WARN("Unable to initialize force feedback: %s", SDL_GetError());
            return;
        }

        /* Check to see what it supports. */
        haptic_query = SDL_HapticQuery(haptic);
        if (!(haptic_query & SDL_HAPTIC_SINE)) {
            SDL_HapticClose(haptic);
            haptic = NULL;
            return;
        }

        DEBUG("   force feedback enabled");
    }
#endif /* SDL_VERSION_ATLEAST(1,3,0) */
}
Example #3
0
JNIEXPORT jint JNICALL Java_at_wisch_joystick_JoystickManager_openFFJoystick (JNIEnv *env, jclass, jint joystickIndex) {
	SDL_Haptic* hapticDevice = SDL_HapticOpenFromJoystick(joysticks[joystickIndex]);
	if (hapticDevice == NULL) {
		// Most likely Joystick does not have FF-capabilities...
		return -4;
	}
	
	int hapticDeviceIndex = SDL_HapticIndex(hapticDevice);
	/* # the previous line did not work with previous versions of SDL 
	   # see http://bugzilla.libsdl.org/show_bug.cgi?id=946
	   # -> had to use the following workaround
	   # (the implementation of SDL_HapticOpenFromJoystick in linux in fact does it it in the same way) */
	/* int hapticDeviceIndex = -5;
	for (int i = 0; i < SDL_NumHaptics(); i++) {
		if (SDL_HapticName(i) != NULL) {
			if (SDL_strcmp(SDL_HapticName(i), SDL_JoystickName(joystickIndex)) == 0) {
		        hapticDeviceIndex = i;
			    break;
			}
        }
    }*/

	if (hapticDeviceIndex < 0) {	
		throwException(env, SDL_GetError());
		return hapticDeviceIndex;
	}	
	ffjoysticks[hapticDeviceIndex] = hapticDevice;
	return hapticDeviceIndex;
}
Example #4
0
void JoyInitHaptic() {
#if 0
    uint8_t i;
    unsigned int haptic_query = 0;
    for (i = 0; i < 2; i++) {
        if (g.PadState[i].JoyDev && SDL_JoystickIsHaptic(g.PadState[i].JoyDev)) {
            if (g.PadState[i].haptic != NULL) {
                SDL_HapticClose(g.PadState[i].haptic);
                g.PadState[i].haptic = NULL;
            }

            g.PadState[i].haptic = SDL_HapticOpenFromJoystick(g.PadState[i].JoyDev);
            if (g.PadState[i].haptic == NULL)
                continue;

            if (SDL_HapticRumbleSupported(g.PadState[i].haptic) == SDL_FALSE) {
                printf("\nRumble not supported\n");
                g.PadState[i].haptic = NULL;
                continue;
            }

            if (SDL_HapticRumbleInit(g.PadState[i].haptic) != 0) {
                printf("\nFailed to initialize rumble: %s\n", SDL_GetError());
                g.PadState[i].haptic = NULL;
                continue;
            }
        }
    }
#endif
}
Example #5
0
bool CSDLPad::OpenDevice()
{
	m_pSDLDevice = SDL_JoystickOpen(m_deviceNo);
	if (m_pSDLDevice)
	{
		// SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK) should skip the accelerometer when 
		// enumerating joysticks, but it doesn't seem to work.  Manually check for it here 
		// and close it.
		// FIXME: Need a more robust way of detecting this (or get SetHint() to work).
		if (strcmp(SDL_JoystickName(m_pSDLDevice), "Android Accelerometer") == 0)
		{
			SDL_JoystickClose(m_pSDLDevice);
			return false;
		}
		m_connected = true;
#if defined(SDL_USE_HAPTIC_FEEDBACK)
		m_pHapticDevice = SDL_HapticOpenFromJoystick(m_pSDLDevice);
		if (m_pHapticDevice && (SDL_HapticQuery(m_pHapticDevice) & SDL_HAPTIC_LEFTRIGHT))
		{
			m_supportsFeedback = true;
		}
		else
		{
			if (m_pHapticDevice) SDL_HapticClose(m_pHapticDevice);
			m_supportsFeedback = false;
		}
#else
		m_supportsFeedback = false;
#endif
		m_curHapticEffect = -1;
		gEnv->pLog->Log("CSDLPad - Gamepad [%d] supports feedback (Y/N): %s", m_deviceNo, m_supportsFeedback ? "Y" : "N");
	}
	return m_pSDLDevice != NULL;
}
Example #6
0
bool JoystickInfo::Init(int id)
{
	Destroy();
	_id = id;

	joy = SDL_JoystickOpen(id);
	if (joy == NULL)
	{
		PAD_LOG("failed to open joystick %d\n", id);
		return false;
	}

	numaxes = SDL_JoystickNumAxes(joy);
	numbuttons = SDL_JoystickNumButtons(joy);
	numhats = SDL_JoystickNumHats(joy);
#if SDL_MAJOR_VERSION >= 2
	devname = SDL_JoystickName(joy);
#else
	devname = SDL_JoystickName(id);
#endif

	vaxisstate.resize(numaxes);
	vbuttonstate.resize(numbuttons);
	vhatstate.resize(numhats);

	// Sixaxis, dualshock3 hack
	// Most buttons are actually axes due to analog pressure support. Only the first 4 buttons
	// are digital (select, start, l3, r3). To avoid conflict just forget the others.
	// Keep the 4 hat buttons too (usb driver). (left pressure does not work with recent kernel). Moreover the pressure
	// work sometime on half axis neg others time in fulll axis. So better keep them as button for the moment
	u32 found_hack = devname.find(string("PLAYSTATION(R)3"));
	if (found_hack != string::npos && numaxes > 4) {
		numbuttons = 4; // (select, start, l3, r3)
		// Enable this hack in bluetooth too. It avoid to restart the onepad gui
		numbuttons += 4; // the 4 hat buttons
	}

#if SDL_MAJOR_VERSION >= 2
	if ( haptic == NULL ) {
		if (!SDL_JoystickIsHaptic(joy)) {
			PAD_LOG("Haptic devices not supported!\n");
		} else {
			haptic = SDL_HapticOpenFromJoystick(joy);
			// upload some default effect
			InitHapticEffect();
		}
	}
#endif

	//PAD_LOG("There are %d buttons, %d axises, and %d hats.\n", numbuttons, numaxes, numhats);
	return true;
}
Example #7
0
void SDLFrontend::initJoystickAndHaptic ()
{
	if (_haptic != nullptr) {
		SDL_HapticClose(_haptic);
		_haptic = nullptr;
	}

	const int joysticks = SDL_NumJoysticks();
	SDL_Haptic *haptic = nullptr;
	for (int i = 0; i < joysticks; i++) {
		const char *name;
		if (SDL_IsGameController(i)) {
			name = SDL_GameControllerNameForIndex(i);
		} else {
			name = SDL_JoystickNameForIndex(i);
		}
		SDL_Joystick *joystick = SDL_JoystickOpen(i);
		info(LOG_CLIENT, String::format("found joystick %s", name ? name : "Unknown Joystick"));
		info(LOG_CLIENT, String::format("joystick axes: %i", SDL_JoystickNumAxes(joystick)));
		info(LOG_CLIENT, String::format("joystick hats: %i", SDL_JoystickNumHats(joystick)));
		info(LOG_CLIENT, String::format("joystick balls: %i", SDL_JoystickNumBalls(joystick)));
		info(LOG_CLIENT, String::format("joystick buttons: %i", SDL_JoystickNumButtons(joystick)));
		if (haptic == nullptr)
			haptic = SDL_HapticOpenFromJoystick(joystick);
	}
	if (!joysticks) {
		info(LOG_CLIENT, "no joysticks found");
	}

	info(LOG_CLIENT, String::format("found %i touch device(s)", SDL_GetNumTouchDevices()));

	info(LOG_CLIENT, String::format("%i haptic devices", SDL_NumHaptics()));
	if (haptic == nullptr && SDL_MouseIsHaptic()) {
		haptic = SDL_HapticOpenFromMouse();
	}
	if (haptic != nullptr) {
		const bool rumbleSupported = SDL_HapticRumbleSupported(haptic) && SDL_HapticRumbleInit(haptic) == 0;
		if (rumbleSupported) {
			info(LOG_CLIENT, "rumble support");
			_haptic = haptic;
		}
	}
	if (_haptic == nullptr) {
		info(LOG_CLIENT, "no rumble support");
	}
}
C4GamePadOpener::C4GamePadOpener(int iGamepad)
{
	int n = iGamepad;
	for (int i = 0; i < SDL_NumJoysticks(); i++)
		if (SDL_IsGameController(i) && n-- == 0)
		{
			controller = SDL_GameControllerOpen(i);
			if (!controller) LogF("SDL: %s", SDL_GetError());
			SDL_Joystick *joystick = SDL_GameControllerGetJoystick(controller);
			haptic = SDL_HapticOpenFromJoystick(joystick);
			if (haptic && SDL_HapticRumbleSupported(haptic))
				SDL_HapticRumbleInit(haptic);
			else
				LogF("Gamepad #%d %s does not support rumbling.", SDL_JoystickInstanceID(joystick), SDL_JoystickName(joystick));
			break;
		}

	if (!controller) LogF("Gamepad %d not available", iGamepad);
}
Example #9
0
void I_InitGamepad(void)
{
    if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC) < 0)
        C_Warning("Gamepad support couldn't be initialized.");
    else
    {
        int numjoysticks = SDL_NumJoysticks();

        for (int i = 0; i < numjoysticks; i++)
            if ((joystick = SDL_JoystickOpen(i)))
                if (SDL_IsGameController(i))
                {
                    gamecontroller = SDL_GameControllerOpen(i);
                    break;
                }

        if (!gamecontroller)
            SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC);
        else
        {
            const char  *name = SDL_GameControllerName(gamecontroller);

            if (*name)
            {
                if (M_StrCaseStr(name, "xinput"))
                    C_Output("An <i><b>XInput</b></i> gamepad is connected.");
                else
                    C_Output("A <i><b>DirectInput</b></i> gamepad called \"%s\" is connected.", name);
            }
            else
                C_Output("A gamepad is connected.");

            if (!(haptic = SDL_HapticOpenFromJoystick(joystick)) || SDL_HapticRumbleInit(haptic) < 0)
                C_Warning("This gamepad doesn't support vibration.");
        }
    }

    gamepadbuttons = 0;
    gamepadthumbLX = 0;
    gamepadthumbLY = 0;
    gamepadthumbRX = 0;
    gamepadthumbRY = 0;
}
Example #10
0
Controller::Controller(){
	SDL_InitSubSystem(SDL_INIT_JOYSTICK);
	SDL_Init(SDL_INIT_HAPTIC);
	SDL_JoystickEventState(SDL_ENABLE);
	joystick = SDL_JoystickOpen(0);
	if (joystick){
		joystickAnalogs.resize(SDL_JoystickNumAxes(joystick));
		joystickButtonHeld.resize(SDL_JoystickNumButtons(joystick));
		joystickButtonPressed.resize(SDL_JoystickNumButtons(joystick));
		joystickButtonReleased.resize(SDL_JoystickNumButtons(joystick));
		joystickDPad.resize(13);
		haptic = SDL_HapticOpenFromJoystick(joystick);
		if (SDL_HapticRumbleSupported(haptic) == SDL_TRUE){
			SDL_HapticRumbleInit(haptic);
			rumbleSupport = true;
		}
		else rumbleSupport = false;
	}
	
}
Example #11
0
int _create_controler(int i) {
    SDL_GameController *controller = SDL_GameControllerOpen(i);
    SDL_Joystick *joy = SDL_GameControllerGetJoystick(controller);

    int idx = _new_controler();

    _G.controller[idx] = controller;

    memory_set(_G.state[idx], 0, sizeof(int) * GAMEPAD_BTN_MAX);

    if (SDL_JoystickIsHaptic(joy) == 1) {
        SDL_Haptic *haptic = SDL_HapticOpenFromJoystick(joy);
        SDL_HapticRumbleInit(haptic);
        _G.haptic[idx] = haptic;

        log_info("input.gamepad", "Gamepad %d has haptic support", i);
    } else {
        _G.haptic[idx] = NULL;
    }

    return idx;
}
Example #12
0
bool Joystick::checkCreateHaptic()
{
	if (!isConnected())
		return false;

	if (!SDL_WasInit(SDL_INIT_HAPTIC) && SDL_InitSubSystem(SDL_INIT_HAPTIC) < 0)
		return false;

	if (haptic && SDL_HapticIndex(haptic) != -1)
		return true;

	if (haptic)
	{
		SDL_HapticClose(haptic);
		haptic = nullptr;
	}

	haptic = SDL_HapticOpenFromJoystick(joyhandle);
	vibration = Vibration();

	return haptic != nullptr;
}
Example #13
0
void test_rumble(int joy_idx)
{
  SDL_Joystick* joy = SDL_JoystickOpen(joy_idx);
  if (!joy)
  {
    fprintf(stderr, "Unable to open joystick %d\n", joy_idx);
  }
  else
  {
    SDL_Haptic* haptic = SDL_HapticOpenFromJoystick(joy);
    if (!haptic)
    {
      fprintf(stderr, "Unable to open haptic on joystick %d\n", joy_idx);
      fprintf(stderr, "SDL_Error: %s\n", SDL_GetError());
    }
    else
    {
      if (!SDL_HapticRumbleSupported(haptic))
      {
        fprintf(stderr, "rumble not supported on joystick %d\n", joy_idx);
      }
      else
      {
        if (SDL_HapticRumbleInit(haptic) != 0)
        {
          fprintf(stderr, "failed to init rumble\n");
        }
        else
        {
          SDL_HapticRumblePlay(haptic, 1.0, 3000);
          SDL_Delay(3000);
        }
      }
      SDL_HapticClose(haptic);
    }
    SDL_JoystickClose(joy);
  }
}
Example #14
0
/****** Initialize GamePad ******/
void DMG_GamePad::init()
{
	//Initialize joystick subsystem
	if(SDL_InitSubSystem(SDL_INIT_JOYSTICK) == -1)
	{
		std::cout<<"JOY::Could not initialize SDL joysticks\n";
		return;
	}

	jstick = NULL;
	jstick = SDL_JoystickOpen(config::joy_id);

	if((jstick == NULL) && (SDL_NumJoysticks() >= 1)) { std::cout<<"JOY::Could not initialize joystick \n"; }
	else if((jstick == NULL) && (SDL_NumJoysticks() == 0)) { std::cout<<"JOY::No joysticks detected \n"; return; }

	rumble = NULL;

	//Open haptics for rumbling
	if(config::use_haptics)
	{
		if(SDL_InitSubSystem(SDL_INIT_HAPTIC) == -1)
		{
			std::cout<<"JOY::Could not initialize SDL haptics\n";
			return;
		}

		rumble = SDL_HapticOpenFromJoystick(jstick);

		if(rumble == NULL) { std::cout<<"JOY::Could not init rumble \n"; }
	
		else
		{
			SDL_HapticRumbleInit(rumble);
			std::cout<<"JOY::Rumble initialized\n";
		}
	}
}
internal void sdl_init_joysticks(struct sdl_event_context *ctx)
{
	unsigned int player;
	int num_joy_sticks, jsi;
	SDL_GameController *controller;
	SDL_Joystick *joystick;
	SDL_Haptic *rumble;

	for (player = 0; player < MAX_CONTROLLERS; ++player) {
		ctx->players[player].controller = NULL;
		ctx->players[player].rumble = NULL;
	}

	num_joy_sticks = SDL_NumJoysticks();
	debug(0, "SDL_NumJoysticks() == %d\n", num_joy_sticks);
	player = 0;
	for (jsi = 0; jsi < num_joy_sticks && player < MAX_CONTROLLERS; ++jsi) {
		if (!SDL_IsGameController(jsi)) {
			debug(0, "SDL_IsGameController(%d) == 0\n", jsi);
			continue;
		}
		controller = SDL_GameControllerOpen(jsi);
		ctx->players[player].controller = controller;
		debug(0, "ctx->players[%u].controller = %p\n", player,
		      (void *)controller);

		joystick = SDL_GameControllerGetJoystick(controller);
		rumble = SDL_HapticOpenFromJoystick(joystick);
		if (SDL_HapticRumbleInit(rumble)) {
			ctx->players[player].rumble = rumble;
		} else {
			SDL_HapticClose(rumble);
		}

		++player;
	}
}
Example #16
0
bool SdlJoystick::init()
{
#if SDL_VERSION_ATLEAST(1,3,0)
   SDL_Init(SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC);
#else
   SDL_Init(SDL_INIT_JOYSTICK);
#endif

   if (mDeviceNumber >= SDL_NumJoysticks())
   {
      vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CRITICAL_LVL)
         << clrOutBOLD(clrRED, "ERROR")
         << ": Added for joystick number " << mDeviceNumber
         << " but there are only " << SDL_NumJoysticks() << " joysticks.\n"
         << vprDEBUG_FLUSH;
      return false;
   }
   mJoystick = SDL_JoystickOpen(mDeviceNumber);
   if (!mJoystick)
   {
      vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CRITICAL_LVL)
         << "ERROR: Failed to open joystick " << mDeviceNumber << ": "
         << SDL_GetError();
      return false;
   }

   mButtons.resize(SDL_JoystickNumButtons(mJoystick), gadget::DigitalState::OFF);
   mAxes.resize(SDL_JoystickNumAxes(mJoystick), 0.0f);

   gadget::Digital::addDigitalSample(mButtons);
   gadget::Analog::addAnalogSample(mAxes);

   cout << "Found Joystick " << mDeviceNumber << ": " << SDL_JoystickName(mDeviceNumber) << endl
        << "              Axis: " << mAxes.size() << endl
        << "           Buttons: " << mButtons.size() << endl
        << "              Hats: " << SDL_JoystickNumHats(mJoystick) << " (Unused)" << endl
        << "             Balls: " << SDL_JoystickNumBalls(mJoystick) << " (Unused)" << endl
#if SDL_VERSION_ATLEAST(1,3,0)
        << "           Haptics: " << (SDL_JoystickIsHaptic(mJoystick) ? "YES" : "NO")
#else
        << "           Haptics: Not supported by SDL 1.2"
#endif
        << endl;

#if SDL_VERSION_ATLEAST(1,3,0)
   if (SDL_JoystickIsHaptic(mJoystick))
   {
      mHaptic = SDL_HapticOpenFromJoystick(mJoystick);
      if (!mHaptic)
      {
         vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CRITICAL_LVL)
            << "ERROR: Failed to initialize haptics on " << mDeviceNumber << ": " << SDL_GetError();
         return true;
      }
   unsigned int cap = getCapabilities();
   cout << "    Loaded Effects: " << getMaxStoredEffects() << endl
        << "    Played Effects: " << getMaxPlayingEffects() << endl
        << "        Axes Count: " << getNumAxes() << endl
        << "       Support for:";
   if (cap & RumbleEffect::CONSTANT)     cout << " constant";
   if (cap & RumbleEffect::SINE)         cout << " sine";
   if (cap & RumbleEffect::SQUARE)       cout << " square";
   if (cap & RumbleEffect::TRIANGLE)     cout << " triangle";
   if (cap & RumbleEffect::SAWTOOTHUP)   cout << " saw-tooth-up";
   if (cap & RumbleEffect::SAWTOOTHDOWN) cout << " saw-tooth-down";
   if (cap & RumbleEffect::RAMP)         cout << " ramp";
   if (cap & RumbleEffect::SPRING)       cout << " spring";
   if (cap & RumbleEffect::DAMPER)       cout << " damper";
   if (cap & RumbleEffect::INERTIA)      cout << " inertia";
   if (cap & RumbleEffect::FRICTION)     cout << " friction";
   if (cap & RumbleEffect::CUSTOM)       cout << " custom";
   if (cap & RumbleEffect::GAIN)         cout << " gain";
   if (cap & RumbleEffect::AUTOCENTER)   cout << " auto-center";
   if (cap & RumbleEffect::STATUS)       cout << " status";
   if (cap & RumbleEffect::PAUSE)        cout << " pause";
   cout << endl;
   }
#endif
   mInitialized = true;
   return true;
}
FDeviceInfoSDL FDeviceSDL::AddDevice(FDeviceIndex DeviceIndex)
{
	FDeviceInfoSDL Device;
	if (SDL_IsGameController(DeviceIndex.value) && bIgnoreGameControllers)
	{
		// Let UE handle it
		return Device;
	}

	Device.DeviceIndex = DeviceIndex;

	Device.Joystick = SDL_JoystickOpen(DeviceIndex.value);
	if (Device.Joystick == nullptr)
	{
		return Device;
	}
	Device.InstanceId = FInstanceId(SDL_JoystickInstanceID(Device.Joystick));

	// DEBUG
	Device.Name = FString(ANSI_TO_TCHAR(SDL_JoystickName(Device.Joystick)));
	UE_LOG(JoystickPluginLog, Log, TEXT("--- %s"), *Device.Name);
	UE_LOG(JoystickPluginLog, Log, TEXT("--- Number of Axis %i"), SDL_JoystickNumAxes(Device.Joystick));
	UE_LOG(JoystickPluginLog, Log, TEXT("--- Number of Balls %i"), SDL_JoystickNumBalls(Device.Joystick));
	UE_LOG(JoystickPluginLog, Log, TEXT("--- Number of Buttons %i"), SDL_JoystickNumButtons(Device.Joystick));
	UE_LOG(JoystickPluginLog, Log, TEXT("--- Number of Hats %i"), SDL_JoystickNumHats(Device.Joystick));

	if (SDL_JoystickIsHaptic(Device.Joystick))
	{
		Device.Haptic = SDL_HapticOpenFromJoystick(Device.Joystick);
		if (Device.Haptic != nullptr)
		{
			UE_LOG(JoystickPluginLog, Log, TEXT("--- Rumble device detected"));

			if (SDL_HapticRumbleInit(Device.Haptic) != 0)
			{
				/*UE_LOG(JoystickPluginLog, Log, TEXT("--- testing Rumble device:"));
				if (SDL_HapticRumblePlay(OutDeviceInfo.Haptic, 0.5, 2000) != 0)
				{
				UE_LOG(JoystickPluginLog, Log, TEXT("--- play Rumble ...."));
				SDL_Delay(2000);
				}
				else
				{
				UE_LOG(JoystickPluginLog, Log, TEXT("--- not successful!"));
				SDL_HapticClose(OutDeviceInfo.Haptic);
				OutDeviceInfo.Haptic = nullptr;
				}*/
			}
		}
	}
	

	for (auto &ExistingDevice : Devices)
	{
		if (ExistingDevice.Value.Joystick == nullptr && ExistingDevice.Value.Name == Device.Name)
		{
			Device.DeviceId = ExistingDevice.Key;
			Devices[Device.DeviceId] = Device;

			DeviceMapping.Add(Device.InstanceId, Device.DeviceId);
			EventInterface->JoystickPluggedIn(Device);
			return Device;
		}
	}

	Device.DeviceId = FDeviceId(Devices.Num());
	Devices.Add(Device.DeviceId, Device);

	DeviceMapping.Add(Device.InstanceId, Device.DeviceId);
	EventInterface->JoystickPluggedIn(Device);
	return Device;
}
Example #18
0
/*
 * 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");
}
int
main(int argc, char *argv[])
{
    SDL_Joystick *joystick = NULL;
    SDL_Haptic *haptic = NULL;
    SDL_JoystickID instance = -1;
    SDL_bool keepGoing = SDL_TRUE;
    int i;
    SDL_bool enable_haptic = SDL_TRUE;
    Uint32 init_subsystems = SDL_INIT_VIDEO | SDL_INIT_JOYSTICK;
    
    for (i = 1; i < argc; ++i) {
        if (SDL_strcasecmp(argv[i], "--nohaptic") == 0) {
            enable_haptic = SDL_FALSE;
        }
    }

    if(enable_haptic) {
        init_subsystems |= SDL_INIT_HAPTIC;
    }
    
    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);	

    SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");

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

    //SDL_CreateWindow("Dummy", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 128, 128, 0);

    SDL_Log("There are %d joysticks at startup\n", SDL_NumJoysticks());
    if (enable_haptic)
        SDL_Log("There are %d haptic devices at startup\n", SDL_NumHaptics());

    while(keepGoing)
    {
        SDL_Event event;
        while(SDL_PollEvent(&event))
        {
            switch(event.type)
            {
                case SDL_QUIT:
                    keepGoing = SDL_FALSE;
                    break;
                case SDL_JOYDEVICEADDED:
                    if (joystick != NULL)
                    {
                        SDL_Log("Only one joystick supported by this test\n");
                    }
                    else
                    {
                        joystick = SDL_JoystickOpen(event.jdevice.which);
                        instance = SDL_JoystickInstanceID(joystick);
                        SDL_Log("Joy Added  : %d : %s\n", event.jdevice.which, SDL_JoystickName(joystick));
                        if (enable_haptic)
                        {
                            if (SDL_JoystickIsHaptic(joystick))
                            {
                                haptic = SDL_HapticOpenFromJoystick(joystick);
                                if (haptic)
                                {
                                    SDL_Log("Joy Haptic Opened\n");
                                    if (SDL_HapticRumbleInit( haptic ) != 0)
                                    {
                                        SDL_Log("Could not init Rumble!: %s\n", SDL_GetError());
                                        SDL_HapticClose(haptic);
                                        haptic = NULL;
                                    }
                                } else {
                                    SDL_Log("Joy haptic open FAILED!: %s\n", SDL_GetError());
                                }
                            }
                            else
                            {
                                SDL_Log("No haptic found\n");
                            }
                        }
                    }
                    break;
                case SDL_JOYDEVICEREMOVED:
                    if (instance == event.jdevice.which)
                    {
                        SDL_Log("Joy Removed: %d\n", event.jdevice.which);
                        instance = -1;
                        if(enable_haptic && haptic)
                        {
                            SDL_HapticClose(haptic);
                            haptic = NULL;
                        }
                        SDL_JoystickClose(joystick);
                        joystick = NULL;
                    } else {
                        SDL_Log("Unknown joystick diconnected\n");
                    }
                    break;
                case SDL_JOYAXISMOTION:
//                    SDL_Log("Axis Move: %d\n", event.jaxis.axis);
                    if (enable_haptic)
                        SDL_HapticRumblePlay(haptic, 0.25, 250);
                    break;
                case SDL_JOYBUTTONDOWN:
                    SDL_Log("Button Press: %d\n", event.jbutton.button);
                    if(enable_haptic && haptic)
                    {
                        SDL_HapticRumblePlay(haptic, 0.25, 250);
                    }
					if (event.jbutton.button == 0) {
						SDL_Log("Exiting due to button press of button 0\n");
						keepGoing = SDL_FALSE;
					}
                    break;
                case SDL_JOYBUTTONUP:
                    SDL_Log("Button Release: %d\n", event.jbutton.button);
                    break;
            }
        }
    }

    SDL_Quit();

    return 0;
}
Example #20
0
int main(int argc, char *argv[]) {
  int opt;
  struct sockaddr_can addr;
  struct canfd_frame frame;
  int running = 1;
  int enable_canfd = 1;
  int play_traffic = 1;
  struct stat st;
  SDL_Event event;

  while ((opt = getopt(argc, argv, "Xdl:s:t:h?")) != -1) {
    switch(opt) {
	case 'l':
		difficulty = atoi(optarg);
		break;
	case 's':
		seed = atoi(optarg);
		break;
	case 't':
		traffic_log = optarg;
		break;
	case 'd':
		debug = 1;
		break;
	case 'X':
		play_traffic = 0;
		break;
	case 'h':
	case '?':
	default:
		usage(NULL);
		break;
    }
  }

  if (optind >= argc) usage("You must specify at least one can device");

  if(stat(traffic_log, &st) == -1) {
	char msg[256];
	snprintf(msg, 255, "CAN Traffic file not found: %s\n", traffic_log);
	usage(msg);
  }

  /* open socket */
  if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
       perror("socket");
       return 1;
  }

  addr.can_family = AF_CAN;

  strcpy(ifr.ifr_name, argv[optind]);
  if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) {
       perror("SIOCGIFINDEX");
       return 1;
  }
  addr.can_ifindex = ifr.ifr_ifindex;

  if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FD_FRAMES,
                 &enable_canfd, sizeof(enable_canfd))){
       printf("error when enabling CAN FD support\n");
       return 1;
  }

  if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
       perror("bind");
       return 1;
  }

  door_id = DEFAULT_DOOR_ID;
  signal_id = DEFAULT_SIGNAL_ID;
  speed_id = DEFAULT_SPEED_ID;

  if (seed) {
	srand(seed);
        door_id = (rand() % 2046) + 1;
        signal_id = (rand() % 2046) + 1;
        speed_id = (rand() % 2046) + 1;
        door_pos = rand() % 9;
        signal_pos = rand() % 9;
        speed_pos = rand() % 8;
        printf("Seed: %d\n", seed);
	door_len = door_pos + 1;
	signal_len = signal_pos + 1;
	speed_len = speed_len + 2;
  }

  if(difficulty > 0) {
	if (door_len < 8) {
		door_len += rand() % (8 - door_len);
	} else {
		door_len = 0;
	}
	if (signal_len < 8) {
		signal_len += rand() % (8 - signal_len);
	} else {
		signal_len = 0;
	}
	if (speed_len < 8) {
		speed_len += rand() % (8 - speed_len);
	} else {
		speed_len = 0;
	}
  }

  if(play_traffic) {
	signal(SIGALRM,(void (*)(int))kill_child);
	play_id = fork();
	if((int)play_id == -1) {
		printf("Error: Couldn't fork bg player\n");
		exit(-1);
	} else if (play_id != 0) {
		play_can_traffic();
	}
  }

  // GUI Setup
  SDL_Window *window = NULL;
  SDL_Surface *screenSurface = NULL;
  if(SDL_Init ( SDL_INIT_VIDEO | SDL_INIT_JOYSTICK ) < 0 ) {
        printf("SDL Could not initializes\n");
        exit(40);
  }
  if( SDL_NumJoysticks() < 1) {
	printf(" Warning: No joysticks connected\n");
  } else {
	if(SDL_IsGameController(0)) {
	  gGameController = SDL_GameControllerOpen(0);
	  if(gGameController == NULL) {
		printf(" Warning: Unable to open game controller. %s\n", SDL_GetError() );
	  } else {
		gJoystick = SDL_GameControllerGetJoystick(gGameController);
		gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
		print_joy_info();
	  }
        } else {
		gJoystick = SDL_JoystickOpen(0);
		if(gJoystick == NULL) {
			printf(" Warning: Could not open joystick\n");
		} else {
			gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
			if (gHaptic == NULL) printf("No Haptic support\n");
			print_joy_info();
		}
	}
  }
  window = SDL_CreateWindow("CANBus Control Panel", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
  if(window == NULL) {
        printf("Window could not be shown\n");
  }
  renderer = SDL_CreateRenderer(window, -1, 0);
  SDL_Surface *image = IMG_Load(get_data("joypad.png"));
  base_texture = SDL_CreateTextureFromSurface(renderer, image);
  SDL_RenderCopy(renderer, base_texture, NULL, NULL);
  SDL_RenderPresent(renderer);
  int button, axis; // Used for checking dynamic joystick mappings

  while(running) {
    while( SDL_PollEvent(&event) != 0 ) {
        switch(event.type) {
            case SDL_QUIT:
                running = 0;
                break;
	    case SDL_WINDOWEVENT:
		switch(event.window.event) {
		case SDL_WINDOWEVENT_ENTER:
		case SDL_WINDOWEVENT_RESIZED:
			redraw_screen();
			break;
		}
	    case SDL_KEYDOWN:
		switch(event.key.keysym.sym) {
		    case SDLK_UP:
			throttle = 1;
			break;
		    case SDLK_LEFT:
			turning = -1;
			break;
		    case SDLK_RIGHT:
			turning = 1;
			break;
		    case SDLK_LSHIFT:
			lock_enabled = 1;
			if(unlock_enabled) send_lock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
			break;
		    case SDLK_RSHIFT:
			unlock_enabled = 1;
			if(lock_enabled) send_unlock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
			break;
		    case SDLK_a:
			if(lock_enabled) {
				send_lock(CAN_DOOR1_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR1_LOCK);
			}
			break;
		    case SDLK_b:
			if(lock_enabled) {
				send_lock(CAN_DOOR2_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR2_LOCK);
			}
			break;
		    case SDLK_x:
			if(lock_enabled) {
				send_lock(CAN_DOOR3_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR3_LOCK);
			}
			break;
		    case SDLK_y:
			if(lock_enabled) {
				send_lock(CAN_DOOR4_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR4_LOCK);
			}
			break;
		}
		kk_check(event.key.keysym.sym);
	   	break;
	    case SDL_KEYUP:
		switch(event.key.keysym.sym) {
		    case SDLK_UP:
			throttle = -1;
			break;
		    case SDLK_LEFT:
		    case SDLK_RIGHT:
			turning = 0;
			break;
		    case SDLK_LSHIFT:
			lock_enabled = 0;
			break;
		    case SDLK_RSHIFT:
			unlock_enabled = 0;
			break;
		}
		break;
	    case SDL_JOYAXISMOTION:
		axis = event.jaxis.axis;
		if(axis == gAxisLeftH) {
			ud(event.jaxis.value);
		} else if(axis == gAxisLeftV) {
			turn(event.jaxis.value);
		} else if(axis == gAxisR2) {
			accelerate(event.jaxis.value);
		} else if(axis == gAxisRightH ||
			  axis == gAxisRightV ||
			  axis == gAxisL2 ||
			  axis == gJoyX ||
			  axis == gJoyY ||
			  axis == gJoyZ) {
			// Do nothing, the axis is known just not connected
		} else {
			if (debug) printf("Unkown axis: %d\n", event.jaxis.axis);
		}
		break;
	    case SDL_JOYBUTTONDOWN:
                button = event.jbutton.button;
		if(button == gButtonLock) {
			lock_enabled = 1;
			if(unlock_enabled) send_lock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
		} else if(button == gButtonUnlock) {
			unlock_enabled = 1;
			if(lock_enabled) send_unlock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
		} else if(button == gButtonA) {
			if(lock_enabled) {
				send_lock(CAN_DOOR1_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR1_LOCK);
			}
			kk_check(SDLK_a);
		} else if (button == gButtonB) {
			if(lock_enabled) {
				send_lock(CAN_DOOR2_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR2_LOCK);
			}
			kk_check(SDLK_b);
		} else if (button == gButtonX) {
			if(lock_enabled) {
				send_lock(CAN_DOOR3_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR3_LOCK);
			}
			kk_check(SDLK_x);
		} else if (button == gButtonY) {
			if(lock_enabled) {
				send_lock(CAN_DOOR4_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR4_LOCK);
			}
			kk_check(SDLK_y);
		} else if (button == gButtonStart) {
			kk_check(SDLK_RETURN);
		} else {
			if(debug) printf("Unassigned button: %d\n", event.jbutton.button);
		}
		break;
	    case SDL_JOYBUTTONUP:
		button = event.jbutton.button;
		if(button == gButtonLock) {
			lock_enabled = 0;
		} else if(button == gButtonUnlock) {
			unlock_enabled = 0;
		} else {
			//if(debug) printf("Unassigned button: %d\n", event.jbutton.button);
		}
		break;
	    case SDL_JOYDEVICEADDED:
		// Only use the first controller
		if(event.cdevice.which == 0) {
			gJoystick = SDL_JoystickOpen(0);
			if(gJoystick) {
				gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
				print_joy_info();
			}
		}
		break;
	    case SDL_JOYDEVICEREMOVED:
		if(event.cdevice.which == 0) {
			SDL_JoystickClose(gJoystick);
			gJoystick = NULL;
		}
		break;
	    case SDL_CONTROLLERDEVICEADDED:
		// Only use the first controller
		if(gGameController == NULL) {
			gGameController = SDL_GameControllerOpen(0);
			gJoystick = SDL_GameControllerGetJoystick(gGameController);
			gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
			print_joy_info();
		}
		break;
	    case SDL_CONTROLLERDEVICEREMOVED:
		if(event.cdevice.which == 0) {
			SDL_GameControllerClose(gGameController);
			gGameController = NULL;
		}
		break;
        }
    }
    currentTime = SDL_GetTicks();
    checkAccel();
    checkTurn();
    SDL_Delay(5);
  }

  kill_child(SIGKILL);
  close(s);
  SDL_DestroyTexture(base_texture);
  SDL_FreeSurface(image);
  SDL_GameControllerClose(gGameController);
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_Quit();

}
Example #21
0
static void sdl_pad_connect(unsigned id)
{
   sdl_joypad_t *pad          = (sdl_joypad_t*)&sdl_pads[id];
   bool success               = false;
   int32_t product            = 0;
   int32_t vendor             = 0;

#ifdef HAVE_SDL2
   SDL_JoystickGUID guid;
   uint16_t *guid_ptr;

   if (SDL_IsGameController(id))
   {
      pad->controller = SDL_GameControllerOpen(id);
      pad->joypad     = SDL_GameControllerGetJoystick(pad->controller);

      success = pad->joypad != NULL && pad->controller != NULL;
   }
   else
#endif
   {
      pad->joypad = SDL_JoystickOpen(id);
      success = pad->joypad != NULL;
   }

   if (!success)
   {
      RARCH_ERR("[SDL]: Couldn't open joystick #%u: %s.\n", id, SDL_GetError());

      if (pad->joypad)
         SDL_JoystickClose(pad->joypad);

      pad->joypad = NULL;

      return;
   }

#ifdef HAVE_SDL2
   guid       = SDL_JoystickGetGUID(pad->joypad);
   guid_ptr   = (uint16_t*)guid.data;
#ifdef __linux
   vendor     = guid_ptr[2];
   product    = guid_ptr[4];
#elif _WIN32
   vendor     = guid_ptr[0];
   product    = guid_ptr[1];
#endif
#endif

   if (!input_autoconfigure_connect(
         sdl_joypad_name(id),
         NULL,
         sdl_joypad.ident,
         id,
         vendor,
         product))
      input_config_set_device_name(id, sdl_joypad_name(id));

   RARCH_LOG("[SDL]: Device #%u (%04x:%04x) connected: %s.\n", id, vendor,
             product, sdl_joypad_name(id));

#ifdef HAVE_SDL2
   if (pad->controller)
   {
      /* SDL_GameController internally supports all axis/button IDs, even if
       * the controller's mapping does not have a binding for it.
       *
       * So, we can claim to support all axes/buttons, and when we try to poll
       * an unbound ID, SDL simply returns the correct unpressed value.
       *
       * Note that, in addition to 0 trackballs, we also have 0 hats. This is
       * because the d-pad is in the button list, as the last 4 enum entries.
       *
       * -flibit
       */
      pad->num_axes    = SDL_CONTROLLER_AXIS_MAX;
      pad->num_buttons = SDL_CONTROLLER_BUTTON_MAX;
      pad->num_hats    = 0;
      pad->num_balls   = 0;

      RARCH_LOG("[SDL]: Device #%u supports game controller api.\n", id);
   }
   else
   {
      pad->num_axes    = SDL_JoystickNumAxes(pad->joypad);
      pad->num_buttons = SDL_JoystickNumButtons(pad->joypad);
      pad->num_hats    = SDL_JoystickNumHats(pad->joypad);
      pad->num_balls   = SDL_JoystickNumBalls(pad->joypad);

      RARCH_LOG("[SDL]: Device #%u has: %u axes, %u buttons, %u hats and %u trackballs.\n",
                id, pad->num_axes, pad->num_buttons, pad->num_hats, pad->num_balls);
   }

   pad->haptic = g_has_haptic ? SDL_HapticOpenFromJoystick(pad->joypad) : NULL;

   if (g_has_haptic && !pad->haptic)
      RARCH_WARN("[SDL]: Couldn't open haptic device of the joypad #%u: %s\n",
                 id, SDL_GetError());

   pad->rumble_effect = -1;

   if (pad->haptic)
   {
      SDL_HapticEffect efx;
      efx.type = SDL_HAPTIC_LEFTRIGHT;
      efx.leftright.type = SDL_HAPTIC_LEFTRIGHT;
      efx.leftright.large_magnitude = efx.leftright.small_magnitude = 0x4000;
      efx.leftright.length = 5000;

      if (SDL_HapticEffectSupported(pad->haptic, &efx) == SDL_FALSE)
      {
         pad->rumble_effect = -2;
         RARCH_WARN("[SDL]: Device #%u does not support rumble.\n", id);
      }
   }
#else
   pad->num_axes    = SDL_JoystickNumAxes(pad->joypad);
   pad->num_buttons = SDL_JoystickNumButtons(pad->joypad);
   pad->num_hats    = SDL_JoystickNumHats(pad->joypad);

   RARCH_LOG("[SDL]: Device #%u has: %u axes, %u buttons, %u hats.\n",
             id, pad->num_axes, pad->num_buttons, pad->num_hats);
#endif
}
Example #22
0
void EventosJoysticks::processarEvento(const SDL_Event& evento)
{
	Joystick* joy;

	switch(evento.type)
	{
	case SDL_JOYAXISMOTION:
		joy = identificarJoystick(evento.jaxis.which);
		if(joy)
		{
			switch(evento.jaxis.axis)
			{
			case SDL_CONTROLLER_AXIS_LEFTX:
				joy->x = evento.caxis.value/32767.0f;
				filtrarInput(joy->x, joy);
				break;

			case SDL_CONTROLLER_AXIS_LEFTY:
				joy->y = evento.caxis.value/32767.0f;
				filtrarInput(joy->y, joy);
				break;

			case SDL_CONTROLLER_AXIS_RIGHTX:
				joy->xDir = evento.caxis.value/32767.0f;
				filtrarInput(joy->xDir, joy);
				break;

			case SDL_CONTROLLER_AXIS_RIGHTY:
				joy->yDir = evento.caxis.value/32767.0f;
				filtrarInput(joy->yDir, joy);
				break;

			case SDL_CONTROLLER_AXIS_TRIGGERLEFT:
				joy->z = evento.caxis.value/32767.0f;
				filtrarInput(joy->z, joy);
				break;

			case SDL_CONTROLLER_AXIS_TRIGGERRIGHT:
				joy->zDir = evento.caxis.value/32767.0f;
				filtrarInput(joy->zDir, joy);
				break;
			}
		}
		break;

	case SDL_CONTROLLERBUTTONDOWN:
		joy = identificarJoystick(evento.cbutton.which);
		if (joy)
		{
			joy->segurando[evento.cbutton.button] = true;

			if (evento.cbutton.state == SDL_PRESSED)
			{
				joy->pressionou[evento.cbutton.button] = true;
			}
		}
		break;

	case SDL_CONTROLLERBUTTONUP:
		joy = identificarJoystick(evento.cbutton.which);
		if (joy)
		{
			joy->segurando[evento.cbutton.button] = false;

			if (evento.cbutton.state == SDL_RELEASED)
			{
				joy->soltou[evento.cbutton.button] = true;
			}
		}
		break;

	case SDL_JOYBUTTONDOWN:
		joy = identificarJoystick(evento.jbutton.which);
		if(joy)
		{
			if (joy->eControle())
			{
				//	para aqui, pois controles são tratados separadamente
				break;
			}

			joy->segurando[evento.jbutton.button] = true;

			if(evento.jbutton.state == SDL_PRESSED)
			{
				joy->pressionou[evento.jbutton.button] = true;
			}
		}

		break;

	case SDL_JOYBUTTONUP:	
		joy = identificarJoystick(evento.jbutton.which);
		if(joy)
		{
			if (joy->eControle())
			{
				//	para aqui, pois controles são tratados separadamente
				break;
			}

			joy->segurando[evento.jbutton.button] = false;

			if(evento.jbutton.state == SDL_RELEASED)
			{
				joy->soltou[evento.jbutton.button] = true;
			}
		}

		break;


	case SDL_JOYDEVICEADDED:
		joy = getPrimeiroJoystickLivre();
		if(joy)
		{
			if (SDL_IsGameController(evento.jdevice.which))
			{
				joy->sdl_controller = SDL_GameControllerOpen(evento.jdevice.which);
				joy->sdl_joystick = SDL_GameControllerGetJoystick(joy->sdl_controller);
			}
			else
			{
				joy->sdl_joystick = SDL_JoystickOpen(evento.jdevice.which);
				joy->sdl_controller = NULL;
			}
			joy->id = nextId;
			joy->sdl_haptic = SDL_HapticOpenFromJoystick(joy->sdl_joystick);
			if(joy->sdl_haptic)
			{
				if(SDL_HapticRumbleSupported(joy->sdl_haptic))
					SDL_HapticRumbleInit(joy->sdl_haptic);
			}
			nextId++;
		}
		break;

	case SDL_JOYDEVICEREMOVED:
		joy = identificarJoystick(evento.jdevice.which);
		if(joy)
		{
			if(joy->sdl_haptic)
			{
				SDL_HapticClose(joy->sdl_haptic);
				joy->sdl_haptic = NULL;
			}

			if (joy->sdl_controller)
			{
				SDL_GameControllerClose(joy->sdl_controller);
			}
			else
			{
				SDL_JoystickClose(joy->sdl_joystick);
			}
			joy->sdl_controller = NULL;
			joy->sdl_joystick = NULL;
			joy->id = -1;
		}
		break;
	}
}
Example #23
0
void Engine_InitSDLControls()
{
    int    NumJoysticks;
    Uint32 init_flags    = SDL_INIT_VIDEO | SDL_INIT_EVENTS;                    // These flags are used in any case.

    if(control_mapper.use_joy == 1)
    {
        init_flags |= SDL_INIT_GAMECONTROLLER;                                  // Update init flags for joystick.

        if(control_mapper.joy_rumble)
        {
            init_flags |= SDL_INIT_HAPTIC;                                      // Update init flags for force feedback.
        }

        SDL_Init(init_flags);

        NumJoysticks = SDL_NumJoysticks();
        if((NumJoysticks < 1) || ((NumJoysticks - 1) < control_mapper.joy_number))
        {
            Sys_DebugLog(LOG_FILENAME, "Error: there is no joystick #%d present.", control_mapper.joy_number);
            return;
        }

        if(SDL_IsGameController(control_mapper.joy_number))                     // If joystick has mapping (e.g. X360 controller)
        {
            SDL_GameControllerEventState(SDL_ENABLE);                           // Use GameController API
            sdl_controller = SDL_GameControllerOpen(control_mapper.joy_number);

            if(!sdl_controller)
            {
                Sys_DebugLog(LOG_FILENAME, "Error: can't open game controller #%d.", control_mapper.joy_number);
                SDL_GameControllerEventState(SDL_DISABLE);                      // If controller init failed, close state.
                control_mapper.use_joy = 0;
            }
            else if(control_mapper.joy_rumble)                                  // Create force feedback interface.
            {
                sdl_haptic = SDL_HapticOpenFromJoystick(SDL_GameControllerGetJoystick(sdl_controller));
                if(!sdl_haptic)
                {
                    Sys_DebugLog(LOG_FILENAME, "Error: can't initialize haptic from game controller #%d.", control_mapper.joy_number);
                }
            }
        }
        else
        {
            SDL_JoystickEventState(SDL_ENABLE);                                 // If joystick isn't mapped, use generic API.
            sdl_joystick = SDL_JoystickOpen(control_mapper.joy_number);

            if(!sdl_joystick)
            {
                Sys_DebugLog(LOG_FILENAME, "Error: can't open joystick #%d.", control_mapper.joy_number);
                SDL_JoystickEventState(SDL_DISABLE);                            // If joystick init failed, close state.
                control_mapper.use_joy = 0;
            }
            else if(control_mapper.joy_rumble)                                  // Create force feedback interface.
            {
                sdl_haptic = SDL_HapticOpenFromJoystick(sdl_joystick);
                if(!sdl_haptic)
                {
                    Sys_DebugLog(LOG_FILENAME, "Error: can't initialize haptic from joystick #%d.", control_mapper.joy_number);
                }
            }
        }

        if(sdl_haptic)                                                          // To check if force feedback is working or not.
        {
            SDL_HapticRumbleInit(sdl_haptic);
            SDL_HapticRumblePlay(sdl_haptic, 1.0, 300);
        }
    }
    else
    {
        SDL_Init(init_flags);
    }
}
Example #24
0
// First time (lazy) initialization.
void
gfctrlJoyInit(void)
{
#ifndef SDL_JOYSTICK
    gfctrlJoyPresent = GFCTRL_JOY_NONE;

    for (int index = 0; index < GFCTRL_JOY_NUMBER; index++) {
		if (!Joysticks[index]) {
			Joysticks[index] = new jsJoystick(index);
		}
    
		// Don't configure the joystick if it doesn't work
		if (Joysticks[index]->notWorking()) {
			delete Joysticks[index];
			Joysticks[index] = 0;
		} else {
			gfctrlJoyPresent = GFCTRL_JOY_PRESENT;
		}
    }
#else
#if SDL_MAJOR_VERSION >= 2
    memset(&cfx, 0, sizeof(cfx));

    if (SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC) < 0) {
#else
    if (SDL_Init(SDL_INIT_JOYSTICK) < 0) {
#endif
        GfLogError("Couldn't initialize SDL: %s\n", SDL_GetError());
        gfctrlJoyPresent = GFCTRL_JOY_UNTESTED;
	return;
    }
#if SDL_MAJOR_VERSION >= 2
    // Ignore the joystick events, we will poll directly as it is faster
    SDL_JoystickEventState(SDL_IGNORE);
#endif
    gfctrlJoyPresent = SDL_NumJoysticks();
    if (gfctrlJoyPresent > GFCTRL_JOY_NUMBER) gfctrlJoyPresent = GFCTRL_JOY_NUMBER;

    for (int index = 0; index < gfctrlJoyPresent; index++) {
		if (!Joysticks[index]) {
			Joysticks[index] = SDL_JoystickOpen(index);
		}
    
		// Don't configure the joystick if it doesn't work
		if (Joysticks[index] ==  NULL) {
			GfLogError("Couldn't open joystick %d: %s\n", index, SDL_GetError());
#if SDL_MAJOR_VERSION >= 2
		} else {
			cfx_timeout[index] = 0;
			rfx_timeout[index] = 0;
			
			// Find which Haptic device relates to this joystick
			Haptics[index] = SDL_HapticOpenFromJoystick(Joysticks[index]);

			if (!Haptics[index]) {
				GfLogInfo("Joystick %d does not support haptic\n", index);
				break;
#if 0
			} else {
				// add an CF effect on startup
				gfctrlJoyConstantForce(index, 50000, 9000);
#endif
			}

			// Check for Rumble capability
			if (SDL_HapticRumbleSupported(Haptics[index]) == SDL_TRUE) {
				if (SDL_HapticRumbleInit(Haptics[index]) != 0) 
					GfLogError("Couldn't init rumble on joystick %d: %s\n", index, SDL_GetError());
#if 0
				else
					gfctrlJoyRumble(index, 0.5);
#endif
			}
#endif
                }
     }
#endif
}

#if SDL_JOYSTICK
void
gfctrlJoyConstantForce(int index, unsigned int level, int dir)
{
#if SDL_MAJOR_VERSION >= 2
	if (!Haptics[index]) return;

	if ((SDL_HapticQuery(Haptics[index]) & SDL_HAPTIC_CONSTANT) == 0) return;

	cfx[index].type = SDL_HAPTIC_CONSTANT;
	cfx[index].constant.direction.type = SDL_HAPTIC_POLAR;
	cfx[index].constant.direction.dir[0] = dir;
	cfx[index].constant.length = 1000;
	cfx[index].constant.level = level;
	cfx[index].constant.attack_length = 0;
	cfx[index].constant.fade_length = 1000;

#if __WIN32__
	if (SDL_HapticGetEffectStatus(Haptics[index], id[index]) == SDL_TRUE)
#else
	// Linux SDL doesn't support checking status at the moment :-(
	if (cfx_timeout[index] > SDL_GetTicks())
#endif
		SDL_HapticUpdateEffect(Haptics[index], id[index], &cfx[index]);
	else {
		SDL_HapticDestroyEffect(Haptics[index], id[index]);
		id[index] = SDL_HapticNewEffect(Haptics[index], &cfx[index]);
		SDL_HapticRunEffect(Haptics[index], id[index], 1);
	}

	cfx_timeout[index] = SDL_GetTicks() + cfx[index].constant.length;
#endif
}

void
gfctrlJoyRumble(int index, float level)
{
#if SDL_MAJOR_VERSION >= 2
	if (!Haptics[index]) return;

	if (SDL_HapticRumbleSupported(Haptics[index]) != SDL_TRUE) return;

	// we have to stop the rumble before updating
	if (rfx_timeout[index] > SDL_GetTicks()) {
		if (SDL_HapticRumbleStop(Haptics[index]) != 0)
			GfLogError("Failed to stop rumble: %s\n", SDL_GetError() );
	}

	if (SDL_HapticRumblePlay(Haptics[index], level, 100) != 0)
		GfLogError("Failed to play rumble: %s\n", SDL_GetError() );

	rfx_timeout[index] = SDL_GetTicks() + 100;
#endif
}
#endif

// Shutdown time.
void
gfctrlJoyShutdown(void)
{
   if (gfctrlJoyPresent != GFCTRL_JOY_UNTESTED)
#ifndef SDL_JOYSTICK
	
		for (int index = 0; index < GFCTRL_JOY_NUMBER; index++)
			delete Joysticks[index];

	
#else
      for (int index = 0; index < gfctrlJoyPresent; index++) {
			SDL_JoystickClose(Joysticks[index]);
			Joysticks[index] = NULL;
#if SDL_MAJOR_VERSION >= 2
			if (Haptics[index]) {
				SDL_HapticClose(Haptics[index]);
				Haptics[index] = NULL;
			}			
#endif
		}
#endif
      gfctrlJoyPresent = GFCTRL_JOY_UNTESTED;
}

/** Create the joystick control
    @ingroup	ctrl
    @return	pointer on a tCtrlJoyInfo structure
		<br>0 .. if no joystick present
    @note	call GfctrlJoyRelease to free the tCtrlJoyInfo structure
    @see	GfctrlJoyRelease
    @see	tCtrlJoyInfo
*/
tCtrlJoyInfo *
GfctrlJoyCreate(void)
{
    if (gfctrlJoyPresent == GFCTRL_JOY_UNTESTED)
       gfctrlJoyInit();

    tCtrlJoyInfo* joyInfo = (tCtrlJoyInfo *)calloc(1, sizeof(tCtrlJoyInfo));

#if SDL_JOYSTICK
    joyInfoCopy = joyInfo;
#endif

    return joyInfo;
}

/** Release the tCtrlJoyInfo structure
    @ingroup	ctrl
    @param	joyInfo	joystick structure
    @return	none
*/
void
GfctrlJoyRelease(tCtrlJoyInfo *joyInfo)
{
    freez(joyInfo);
}
Example #25
0
static void sdl_pad_connect(unsigned id)
{
   sdl_joypad_t *pad          = (sdl_joypad_t*)&sdl_pads[id];
   bool success               = false;
   int32_t product            = 0;
   int32_t vendor             = 0;
   settings_t *settings       = config_get_ptr();
   autoconfig_params_t params = {{0}};

#ifdef HAVE_SDL2
   SDL_JoystickGUID guid;
   uint16_t *guid_ptr;

   if (SDL_IsGameController(id))
   {
      pad->controller = SDL_GameControllerOpen(id);
      pad->joypad     = SDL_GameControllerGetJoystick(pad->controller);

      success = pad->joypad != NULL && pad->controller != NULL;
   }
   else
#endif
   {
      pad->joypad = SDL_JoystickOpen(id);
      success = pad->joypad != NULL;
   }

   if (!success)
   {
      RARCH_ERR("[SDL]: Couldn't open joystick #%u: %s.\n", id, SDL_GetError());

      if (pad->joypad)
         SDL_JoystickClose(pad->joypad);

      pad->joypad = NULL;

      return;
   }

   strlcpy(settings->input.device_names[id], sdl_pad_name(id), sizeof(settings->input.device_names[id]));

#ifdef HAVE_SDL2
   guid       = SDL_JoystickGetGUID(pad->joypad);
   guid_ptr   = (uint16_t*)guid.data;
#ifdef __linux
   vendor     = guid_ptr[2];
   product    = guid_ptr[4];
#elif _WIN32
   vendor     = guid_ptr[0];
   product    = guid_ptr[1];
#endif
#endif
   params.idx = id;
   strlcpy(params.name, sdl_pad_name(id), sizeof(params.name));
   params.vid = vendor;
   params.pid = product;
   strlcpy(params.driver, sdl_joypad.ident, sizeof(params.driver));

   input_config_autoconfigure_joypad(&params);

   RARCH_LOG("[SDL]: Device #%u (%04x:%04x) connected: %s.\n", id, vendor,
             product, sdl_pad_name(id));

#ifdef HAVE_SDL2

   if (pad->controller)
      RARCH_LOG("[SDL]: Device #%u supports game controller api.\n", id);

   pad->haptic = g_has_haptic ? SDL_HapticOpenFromJoystick(pad->joypad) : NULL;

   if (g_has_haptic && !pad->haptic)
      RARCH_WARN("[SDL]: Couldn't open haptic device of the joypad #%u: %s\n",
                 id, SDL_GetError());

   pad->rumble_effect = -1;

   if (pad->haptic)
   {
      SDL_HapticEffect efx;
      efx.type = SDL_HAPTIC_LEFTRIGHT;
      efx.leftright.type = SDL_HAPTIC_LEFTRIGHT;
      efx.leftright.large_magnitude = efx.leftright.small_magnitude = 0x4000;
      efx.leftright.length = 5000;

      if (SDL_HapticEffectSupported(pad->haptic, &efx) == SDL_FALSE)
      {
         pad->rumble_effect = -2;
         RARCH_WARN("[SDL]: Device #%u does not support rumble.\n", id);
      }
   }
#endif

   pad->num_axes    = SDL_JoystickNumAxes(pad->joypad);
   pad->num_buttons = SDL_JoystickNumButtons(pad->joypad);
   pad->num_hats    = SDL_JoystickNumHats(pad->joypad);

#ifdef HAVE_SDL2
   pad->num_balls   = SDL_JoystickNumBalls(pad->joypad);

   RARCH_LOG("[SDL]: Device #%u has: %u axes, %u buttons, %u hats and %u trackballs.\n",
             id, pad->num_axes, pad->num_buttons, pad->num_hats, pad->num_balls);
#else
   RARCH_LOG("[SDL]: Device #%u has: %u axes, %u buttons, %u hats.\n",
             id, pad->num_axes, pad->num_buttons, pad->num_hats);
#endif
}
Example #26
0
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

}
Example #27
0
SdlManager::SdlController::SdlController(SDL_GameController* controller, SDL_Joystick* joystick)
: Controller(SDL_JoystickInstanceID(joystick))
, controller(controller)
, haptic(SDL_HapticOpenFromJoystick(joystick))
, hapticEffectIndex(-1)
{}
Example #28
0
bool input_init(void)
{
	memset(inputs, 0, sizeof(inputs));
	memset(lastinputs, 0, sizeof(lastinputs));
	memset(mappings, -1, sizeof(mappings));
	for (int i=0;i<INPUT_COUNT;i++)
	{
	    mappings[i].key=-1;
	    mappings[i].jbut=-1;
	    mappings[i].jhat=-1;
	    mappings[i].jaxis=-1;
	}
	
	// default mappings
	mappings[LEFTKEY].key      = SDLK_LEFT;
	mappings[RIGHTKEY].key     = SDLK_RIGHT;
	mappings[UPKEY].key        = SDLK_UP;
	mappings[DOWNKEY].key      = SDLK_DOWN;
	mappings[JUMPKEY].key      = SDLK_z;
	mappings[FIREKEY].key      = SDLK_x;
	mappings[PREVWPNKEY].key   = SDLK_a;
	mappings[NEXTWPNKEY].key   = SDLK_s;
	mappings[INVENTORYKEY].key = SDLK_q;
	mappings[MAPSYSTEMKEY].key = SDLK_w;
	
	mappings[ESCKEY].key = SDLK_ESCAPE;
	
	mappings[F1KEY].key  = SDLK_F1;
	mappings[F2KEY].key  = SDLK_F2;
	mappings[F3KEY].key  = SDLK_F3;
	mappings[F4KEY].key  = SDLK_F4;
	mappings[F5KEY].key  = SDLK_F5;
	mappings[F6KEY].key  = SDLK_F6;
	mappings[F7KEY].key  = SDLK_F7;
	mappings[F8KEY].key  = SDLK_F8;
	mappings[F9KEY].key  = SDLK_F9;
	mappings[F10KEY].key = SDLK_F10;
	mappings[F11KEY].key = SDLK_F11;
	mappings[F12KEY].key = SDLK_F12;
	
	mappings[FREEZE_FRAME_KEY].key  = SDLK_SPACE;
	mappings[FRAME_ADVANCE_KEY].key = SDLK_c;
	mappings[DEBUG_FLY_KEY].key     = SDLK_v;

	mappings[HOMEKEY].key  = SDLK_HOME;
	mappings[ENDKEY].key   = SDLK_END;
	mappings[ENTERKEY].key = SDLK_RETURN;
	
	SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC);
	if (SDL_NumJoysticks() > 0) {
	    // Open joystick
	    joy = SDL_JoystickOpen(0);
	
	    if (joy) {
	        stat("Opened Joystick 0");
	        stat("Name: %s", SDL_JoystickNameForIndex(0));
	        stat("Number of Axes: %d", SDL_JoystickNumAxes(joy));
	        stat("Number of Buttons: %d", SDL_JoystickNumButtons(joy));
	        stat("Number of Balls: %d", SDL_JoystickNumBalls(joy));
	        haptic = SDL_HapticOpenFromJoystick( joy );
	        if (haptic == NULL)
	        {
	            stat("No force feedback support");
	        }
	        else
	        {
	            if (SDL_HapticRumbleInit( haptic ) != 0)
	                stat("Coiuldn't init simple rumble");
	        }
	    } else {
	        stat("Couldn't open Joystick 0");
	    }
	                                                                    
	}
	return 0;
}
Example #29
0
bool init() {
  //Initialization flag
  bool success = true;

  //Initialize SDL
  if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC ) < 0 ) {
    printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() );
    success = false;
  } else {
    //Set texture filtering to linear
    if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) ) {
      printf( "Warning: Linear texture filtering not enabled!" );
    }

    //Check for joysticks
    if( SDL_NumJoysticks() < 1 ) {
      printf( "Warning: No joysticks connected!\n" );
    } else {
      //Load joystick
      gGameController = SDL_JoystickOpen( 0 );
      if( gGameController == NULL ) {
        printf( "Warning: Unable to open game controller! SDL Error: %s\n", SDL_GetError() );
      } else {
        //Get controller haptic device
        gControllerHaptic = SDL_HapticOpenFromJoystick( gGameController );
        if( gControllerHaptic == NULL ) {
          printf( "Warning: Controller does not support haptics! SDL Error: %s\n", SDL_GetError() );
        } else {
          //Get initialize rumble
          if( SDL_HapticRumbleInit( gControllerHaptic ) < 0 ) {
            printf( "Warning: Unable to initialize rumble! SDL Error: %s\n", SDL_GetError() );
          }
        }
      }
    }

    //Create window
    gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
    if( gWindow == NULL ) {
      printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() );
      success = false;
    } else {
      //Create vsynced renderer for window
      gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC );
      if( gRenderer == NULL ) {
        printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
        success = false;
      } else {
        //Initialize renderer color
        SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );

        //Initialize PNG loading
        int imgFlags = IMG_INIT_PNG;
        if( !( IMG_Init( imgFlags ) & imgFlags ) ) {
          printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
          success = false;
        }
      }
    }
  }

  return success;
}