//Disable all dinput devices for xinput controllers public void Lock_DX_Devices() { var directInput = new DirectInput(); try { IList<DeviceInstance> devicelist = directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AttachedOnly); foreach (DeviceInstance cdevice in devicelist) { if (cdevice.InstanceName.Trim('\0') == XINPUT_NAME) { var joystick = new Joystick(directInput, cdevice.InstanceGuid); joystick.Acquire(); Guid deviceGUID = joystick.Properties.ClassGuid; string devicePath = joystick.Properties.InterfacePath; joystick.Unacquire(); string[] dpstlit = devicePath.Split('#'); devicePath = @"HID\" + dpstlit[1].ToUpper() + @"\" + dpstlit[2].ToUpper(); lockedDevices.Add(new DeviceID(deviceGUID, devicePath)); DeviceHelper.SetDeviceEnabled(deviceGUID, devicePath, false); } } } finally { directInput.Dispose(); } }
/// <summary> /// 番号指定でデバイス生成。番号のデバイスが存在しなければ例外を投げる。 /// </summary> /// <param name="window"></param> /// <param name="padNumber">0始まり</param> public GamePadDevice(int padNumber, DirectInput directInput) { var devices = GetDevices(directInput); if (devices.Count <= padNumber) { throw new Exception("指定された数のパッドがつながれていない"); } try { Stick = new Joystick(directInput, devices[padNumber].InstanceGuid); //Stick.SetCooperativeLevel(window, CooperativeLevel.Exclusive | CooperativeLevel.Foreground); } catch (Exception e) { throw new Exception("パッドの初期化に失敗", e); } ///スティックの範囲設定 foreach (var item in Stick.GetObjects()) { //if ((item.ObjectType & .Axis) != 0) //{ // Stick.GetObjectPropertiesById((int)item.ObjectType).SetRange(-1000, 1000); //} } Stick.Acquire(); }
private static void HandleJoystick() { // Initialize DirectInput var directInput = new DirectInput(); // Find a Joystick Guid var joystickGuid = Guid.Empty; foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)) joystickGuid = deviceInstance.InstanceGuid; // If Gamepad not found, look for a Joystick if (joystickGuid == Guid.Empty) foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) joystickGuid = deviceInstance.InstanceGuid; // If Joystick not found, throws an error if (joystickGuid == Guid.Empty) { Debug.WriteLine("No Gamepad found."); Environment.Exit(1); } // Instantiate the joystick var joystick = new Joystick(directInput, joystickGuid); Debug.WriteLine("Found Gamepad with GUID: {0}", joystickGuid); // Set BufferSize in order to use buffered data. joystick.Properties.BufferSize = 128; // Acquire the joystick joystick.Acquire(); // Poll events from joystick every 1 millisecond var timer = Observable.Interval(TimeSpan.FromMilliseconds(1)); timer // Get all joystick input .SelectMany(_ => { joystick.Poll(); return joystick.GetBufferedData(); }) // Filter only menu key button (xbox one controller) .Where(a => a.Offset == JoystickOffset.Buttons6) // Input will contain UP and Down button events .Buffer(2) // If button was pressed longer than a second .Where(t => (TimeSpan.FromMilliseconds(t.Last().Timestamp) - TimeSpan.FromMilliseconds(t.First().Timestamp)).TotalSeconds >= 1) // Press and hold F key for 1.5s .Subscribe(t => { SendKeyDown(KeyCode.KEY_F); System.Threading.Thread.Sleep(1500); SendKeyUp(KeyCode.KEY_F); }); }
public GamepadReader() { Buttons = _buttons; Analogs = _analogs; _dinput = new DirectInput(); var devices = _dinput.GetDevices (DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly); if (devices.Count < 1) { throw new IOException ("GamepadReader could not find a connected gamepad."); } _joystick = new Joystick (_dinput, devices[0].InstanceGuid); foreach (var obj in _joystick.GetObjects()) { if ((obj.ObjectType & ObjectDeviceType.Axis) != 0) { _joystick.GetObjectPropertiesById ((int)obj.ObjectType).SetRange (-RANGE, RANGE); } } if (_joystick.Acquire().IsFailure) { throw new IOException ("Connected gamepad could not be acquired."); } _timer = new DispatcherTimer (); _timer.Interval = TimeSpan.FromMilliseconds (TIMER_MS); _timer.Tick += tick; _timer.Start (); }
private Joystick GetJoystick() { var directInput = new DirectInput(); var form = new Form(); foreach (var device in directInput.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly)) { var controller = new Joystick(directInput, device.InstanceGuid); controller.SetCooperativeLevel(form.Handle, CooperativeLevel.Exclusive | CooperativeLevel.Background); var retries = 0; while (controller.Acquire().IsFailure) { retries++; if (retries > 500) throw new Exception("Couldnt acquire SlimDX stick"); } if (controller.Information.InstanceName.Contains("PPJoy")) { foreach (DeviceObjectInstance deviceObject in controller.GetObjects()) { if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0) controller.GetObjectPropertiesById((int)deviceObject.ObjectType).SetRange(-1000, 1000); } return controller; } } return null; }
public DirectInputManager() { var directInput = new DirectInput(); // Prefer a Driving device but make do with fallback to a Joystick if we have to var deviceInstance = FindAttachedDevice(directInput, DeviceType.Driving); if (null == deviceInstance) deviceInstance = FindAttachedDevice(directInput, DeviceType.Joystick); if (null == deviceInstance) throw new Exception("No Driving or Joystick devices attached."); joystickType = (DeviceType.Driving == deviceInstance.Type ? JoystickTypes.Driving : JoystickTypes.Joystick); // A little debug spew is often good for you Log.Spew("First Suitable Device Selected \"" + deviceInstance.InstanceName + "\":"); Log.Spew("\tProductName: " + deviceInstance.ProductName); Log.Spew("\tType: " + deviceInstance.Type); Log.Spew("\tSubType: " + deviceInstance.Subtype); // Data for both Driving and Joystick device types is received via Joystick joystick = new Joystick(directInput, deviceInstance.InstanceGuid); IntPtr consoleWindowHandle = GetConsoleWindow(); if (IntPtr.Zero != consoleWindowHandle) { CooperativeLevel cooperativeLevel = CooperativeLevel.Background | CooperativeLevel.Nonexclusive; Log.Spew("Console window cooperative level: " + cooperativeLevel); if (!joystick.SetCooperativeLevel(consoleWindowHandle, cooperativeLevel).IsSuccess) throw new Exception("Failed to set cooperative level for DirectInput device in console window."); } var result = joystick.Acquire(); if (!result.IsSuccess) throw new Exception("Failed to acquire DirectInput device."); Log.Spew("Joystick acquired."); }
public override void Reconnect() { // search for devices foreach (DeviceInstance device in _DInput.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly)) { // create the device try { _Joy = new Joystick(_DInput, device.InstanceGuid); _Joy.SetCooperativeLevel(wnd_int, CooperativeLevel.Nonexclusive | CooperativeLevel.Background); break; } catch (DirectInputException) { } } if (_Joy == null) { IsConnected = false; Name = ""; Type = ""; return; } _Joy.Acquire(); IsConnected = true; Name = _Joy.Information.ProductName; Type = "DirectInput"; }
public void InitializeController(Guid initGuid) { controllerGuid = Guid.Empty; var deviceInst = input.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly); if (deviceInst.Count == 0) { deviceInst = input.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AttachedOnly); } if (deviceInst.Count > 0) { foreach (var device in deviceInst) { if (device.InstanceGuid == initGuid) { controllerGuid = initGuid; } } if (controllerGuid == Guid.Empty) { controllerGuid = deviceInst[0].InstanceGuid; } controller = new Joystick(input, controllerGuid); controller.Acquire(); defaultControllerState = controller.GetCurrentState(); } }
/// /// Construct, attach the joystick /// public SimpleJoystick() { DirectInput dinput = new DirectInput(); // Search for device foreach (DeviceInstance device in dinput.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly)) { // Create device try { Joystick = new Joystick(dinput, device.InstanceGuid); break; } catch (DirectInputException) { } } if (Joystick == null) throw new Exception("No joystick found"); foreach (DeviceObjectInstance deviceObject in Joystick.GetObjects()) { if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0) Joystick.GetObjectPropertiesById((int)deviceObject.ObjectType).SetRange(-100, 100); } // Acquire sdevice Joystick.Acquire(); }
public MainController() { var directInput = new DirectInput(); LogicState = new LogicState(); foreach (var deviceInstance in directInput.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly)) { try { gamepad = new Joystick(directInput, deviceInstance.InstanceGuid); gamepad.SetCooperativeLevel(Parent, CooperativeLevel.Exclusive | CooperativeLevel.Foreground); break; } catch (DirectInputException) { } } if (gamepad == null) return; foreach (var deviceObject in gamepad.GetObjects()) { if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0) gamepad.GetObjectPropertiesById((int) deviceObject.ObjectType).SetRange(-1000, 1000); } gamepad.Acquire(); }
public static void Initialize() { if (dinput == null) dinput = new DirectInput(); Devices = new List<GamePad>(); foreach (DeviceInstance device in dinput.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly)) { Console.WriteLine("joydevice: {0} `{1}`", device.InstanceGuid, device.ProductName); if (device.ProductName.Contains("XBOX 360")) continue; // Don't input XBOX 360 controllers into here; we'll process them via XInput (there are limitations in some trigger axes when xbox pads go over xinput) var joystick = new Joystick(dinput, device.InstanceGuid); joystick.SetCooperativeLevel(GlobalWin.MainForm.Handle, CooperativeLevel.Background | CooperativeLevel.Nonexclusive); foreach (DeviceObjectInstance deviceObject in joystick.GetObjects()) { if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0) joystick.GetObjectPropertiesById((int)deviceObject.ObjectType).SetRange(-1000, 1000); } joystick.Acquire(); GamePad p = new GamePad(device.InstanceName, device.InstanceGuid, joystick); Devices.Add(p); } }
private void btnOpenPad_Click(object sender, EventArgs e) { if (jp != null) jp.Dispose(); jp = new Joystick(di, (cbPad.SelectedItem as xJoypad).dix.InstanceGuid); jp.Acquire(); lblPadStatus.Text = "Open: " + jp.Information.InstanceName; }
public GamePad() { // Initialize DirectInput directInput = new DirectInput(); // Find a Joystick Guid joystickGuid = Guid.Empty; // Find a Gamepad foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)) joystickGuid = deviceInstance.InstanceGuid; // If Gamepad not found, look for a Joystick if (joystickGuid == Guid.Empty) foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) joystickGuid = deviceInstance.InstanceGuid; // If Joystick not found, throws an error if (joystickGuid == Guid.Empty) { Logger.Log(this, "No joystick/Gamepad found.", 2); } else { // Instantiate the joystick joystick = new Joystick(directInput, joystickGuid); Logger.Log(this, String.Format("Found Joystick/Gamepad with GUID: {0}", joystickGuid), 1); // Set BufferSize in order to use buffered data. joystick.Properties.BufferSize = 128; // Acquire the joystick joystick.Acquire(); // Poll events from joystick //while (true) //{ // joystick.Poll(); // var datas = joystick.GetBufferedData(); // foreach (var state in datas) // Console.WriteLine(state); //} timer = new Timer(); timer.Interval = TIMER_INTERVAL_IN_MS; timer.Tick += new EventHandler(timer_Tick); timer.Start(); } }
private void UseDevices(IList<DeviceInstance> devices) { var guid = devices[0].InstanceGuid; // use first one _joyStick = new Joystick(directInput, guid); _joyStick.Properties.BufferSize = 128; // enable buffer _joyStick.Acquire(); var timer = new DispatcherTimer(); // Timer(onTimer, null, 100); timer.Tick += new EventHandler(timer_Tick); timer.Interval = new TimeSpan(0, 0, 1); timer.Start(); }
static void MainForJoystick() { // Initialize DirectInput var directInput = new DirectInput(); // Find a Joystick Guid var joystickGuid = Guid.Empty; foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)) joystickGuid = deviceInstance.InstanceGuid; // If Gamepad not found, look for a Joystick if (joystickGuid == Guid.Empty) foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) joystickGuid = deviceInstance.InstanceGuid; // If Joystick not found, throws an error if (joystickGuid == Guid.Empty) { Console.WriteLine("No joystick/Gamepad found."); Console.ReadKey(); Environment.Exit(1); } // Instantiate the joystick var joystick = new Joystick(directInput, joystickGuid); Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid); // Query all suported ForceFeedback effects var allEffects = joystick.GetEffects(); foreach (var effectInfo in allEffects) Console.WriteLine("Effect available {0}", effectInfo.Name); // Set BufferSize in order to use buffered data. joystick.Properties.BufferSize = 128; // Acquire the joystick joystick.Acquire(); // Poll events from joystick while (true) { joystick.Poll(); var datas = joystick.GetBufferedData(); foreach (var state in datas) Console.WriteLine(state); } }
public void Acquire(Form parent) { var dinput = new DirectInput(); Pad = new Joystick(dinput, Guid); foreach (DeviceObjectInstance doi in Pad.GetObjects(ObjectDeviceType.Axis)) { Pad.GetObjectPropertiesById((int) doi.ObjectType).SetRange(-5000, 5000); } Pad.Properties.AxisMode = DeviceAxisMode.Absolute; Pad.SetCooperativeLevel(parent, (CooperativeLevel.Nonexclusive | CooperativeLevel.Background)); ButtonCount = Pad.Capabilities.ButtonCount; Pad.Acquire(); }
/// <summary> /// Initializes a new instance of the <see cref="InputDeviceImp"/> class. /// </summary> /// <param name="instance">The DeviceInstance.</param> public InputDeviceImp(DeviceInstance instance) { _controller = instance; _deadZone = 0.1f; buttonsPressed = new bool[100]; _joystick = new Joystick(new DirectInput(), _controller.InstanceGuid); foreach (DeviceObjectInstance deviceObject in _joystick.GetObjects()) { if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0) _joystick.GetObjectPropertiesById((int)deviceObject.ObjectType).SetRange(-1000, 1000); } _joystick.Acquire(); }
public void getFirstPressedButton() { while (listening) { foreach (var deviceInstance in directInput.GetDevices(DeviceType.Driving, DeviceEnumerationFlags.AllDevices)) { Guid joystickGuid = deviceInstance.InstanceGuid; if (joystickGuid == Guid.Empty) { listening = false; } else { // Instantiate the joystick var joystick = new Joystick(directInput, joystickGuid); Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid); // Acquire the joystick joystick.Acquire(); JoystickState state = joystick.GetCurrentState(); Boolean[] buttons = state.Buttons; Boolean useThisJoystick = false; for (int i = 0; i < buttons.Count(); i++) { if (buttons[i]) { this.joystickToUse = joystick; this.buttonIndex = i; Console.WriteLine("Using button index " + buttonIndex + " for device guid " + joystickGuid); listening = false; useThisJoystick = true; break; } } if (!useThisJoystick) { joystick.Unacquire(); } } } Thread.Sleep(1000); } Console.WriteLine("Got button " + buttonIndex); }
public override object CreateGlobal() { var directInput = new DirectInput(); var handle = Process.GetCurrentProcess().MainWindowHandle; devices = new List<Device>(); foreach (var device in directInput.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly)) { var controller = new Joystick(directInput, device.InstanceGuid); controller.SetCooperativeLevel(handle, CooperativeLevel.Exclusive | CooperativeLevel.Background); controller.Acquire(); devices.Add(new Device(controller)); } return devices.Select(d => new JoystickGlobal(d)).ToArray(); }
private void inputComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (joystick != null) { stopInput = true; joystick.Unacquire(); joystick = null; } DeviceInstance device = devices.Find(i => i.InstanceName == (string)inputComboBox.SelectedItem); if (device != null) { joystick = new Joystick(directInput, device.InstanceGuid); joystick.Properties.BufferSize = 128; joystick.Acquire(); } stopInput = false; inputThread = new Thread(ProcessInput); inputThread.Start(); }
void CreateDevice() { // make sure that DirectInput has been initialized DirectInput dinput = new DirectInput(); // search for devices foreach (DeviceInstance device in dinput.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly)) { // create the device try { joystick = new Joystick(dinput, device.InstanceGuid); joystick.SetCooperativeLevel(this, CooperativeLevel.Exclusive | CooperativeLevel.Foreground); break; } catch (DirectInputException) { } } if (joystick == null) { MessageBox.Show("There are no joysticks attached to the system."); return; } foreach (DeviceObjectInstance deviceObject in joystick.GetObjects()) { if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0) joystick.GetObjectPropertiesById((int)deviceObject.ObjectType).SetRange(-1000, 1000); UpdateControl(deviceObject); } // acquire the device joystick.Acquire(); // set the timer to go off 12 times a second to read input // NOTE: Normally applications would read this much faster. // This rate is for demonstration purposes only. timer.Interval = 1000 / 12; timer.Start(); }
public Manual() { // Initialize DirectInput var directInput = new DirectInput(); // Find a Joystick Guid var joystickGuid = Guid.Empty; foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)) joystickGuid = deviceInstance.InstanceGuid; // If Gamepad not found, look for a Joystick if (joystickGuid == Guid.Empty) foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) joystickGuid = deviceInstance.InstanceGuid; // If Joystick not found, throws an error if (joystickGuid != Guid.Empty) { //fix running code without controller //Environment.Exit(1); // Instantiate the joystick joystick = new Joystick(directInput, joystickGuid); Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid); // Query all suported ForceFeedback effects var allEffects = joystick.GetEffects(); foreach (var effectInfo in allEffects) Console.WriteLine("Effect available {0}", effectInfo.Name); // Set BufferSize in order to use buffered data. joystick.Properties.BufferSize = 128; // Acquire the joystick joystick.Acquire(); ControllerOn = true; } }
public void Update() { if (_keyboard.Acquire().IsFailure || _mouse.Acquire().IsFailure || (_joystick1?.Acquire().IsFailure ?? false)) { return; } _keyboardStateLast = _keyboardStateCurrent; _keyboardStateCurrent = _keyboard.GetCurrentState(); _mouseStateLast = _mouseStateCurrent; _mouseStateCurrent = _mouse.GetCurrentState(); _joy1StateLast = _joy1StateCurrent; _joy1StateCurrent = _joystick1?.GetCurrentState(); if (_controller1.IsConnected) { _controller1StateLast = _controller1StateCurrent; _controller1StateCurrent = _controller1.GetState().Gamepad; } }
// --- INITIALIZTION --- public int GetSticks(IMatchDisplay form) { _form = form; DirectInput Input = new DirectInput(); List<Joystick> sticks = new List<Joystick>(); // Creates the list of joysticks connected to the computer via USB. foreach (DeviceInstance device in Input.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly)) { // Creates a joystick for each game device in USB Ports try { var stick = new Joystick(Input, device.InstanceGuid); stick.Acquire(); // Gets the joysticks properties and sets the range for them. foreach (DeviceObjectInstance deviceObject in stick.GetObjects()) { if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0) stick.GetObjectPropertiesById((int)deviceObject.ObjectType).SetRange(-100, 100); } // Adds how ever many joysticks are connected to the computer into the sticks list. sticks.Add(stick); } catch (DirectInputException) { } } Sticks = sticks.ToArray(); var count = Sticks.Length; if (count > 0) { tm1939LoadSticks(); } return count; // sticks.ToArray(); }
public Boolean Connect() { // Joystick finder code adapted from SharpDX Samples - (c) Alexandre Mutel 2012 Guid joystickGuid = Guid.Empty; foreach (DeviceInstance deviceInstance in di.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)) joystickGuid = deviceInstance.InstanceGuid; if (joystickGuid == Guid.Empty) foreach (DeviceInstance deviceInstance in di.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) joystickGuid = deviceInstance.InstanceGuid; if(joystickGuid == Guid.Empty) { MessageBox.Show("No joystick found."); return false; } joystick = new Joystick(di, joystickGuid); joystick.Properties.BufferSize = 128; joystick.Acquire(); return true; }
public static Joystick FindGamepad() { // Initialize DirectInput var directInput = new DirectInput(); // Find a Joystick Guid var joystickGuid = Guid.Empty; foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)) joystickGuid = deviceInstance.InstanceGuid; // If Gamepad not found, look for a Joystick if (joystickGuid == Guid.Empty) foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) joystickGuid = deviceInstance.InstanceGuid; // If Joystick not found, throws an error GamePadConnected = true; if (joystickGuid == Guid.Empty) { MainWindow.GPID = "No Gamepad found."; GamePadConnected = false; //Environment.Exit(1); } // Instantiate the joystick var joystick = new Joystick(directInput, joystickGuid); MainWindow.GPID = "Gamepad GUID: " + joystickGuid; // Query all suported ForceFeedback effects var allEffects = joystick.GetEffects(); foreach (var effectInfo in allEffects) Console.WriteLine("Effect available {0}", effectInfo.Name); // Set BufferSize in order to use buffered data. joystick.Properties.BufferSize = 128; // Acquire the joystick joystick.Acquire(); // Poll events from joystick // while (true) // { // joystick.Poll(); // var datas = joystick.GetBufferedData(); // foreach (var state in datas) // Console.WriteLine(state); //} return joystick; }
static void Main(string[] args) { if (client == null) { // create client instance client = new MqttClient(MQTT_BROKER_ADDRESS); string clientId = Guid.NewGuid().ToString(); client.Connect(clientId, "mifmasterz", "123qweasd"); SubscribeMessage(); } // Initialize DirectInput var directInput = new DirectInput(); // Find a Joystick Guid var joystickGuid = Guid.Empty; foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)) { joystickGuid = deviceInstance.InstanceGuid; } // If Gamepad not found, look for a Joystick if (joystickGuid == Guid.Empty) { foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) { joystickGuid = deviceInstance.InstanceGuid; } } // If Joystick not found, throws an error if (joystickGuid == Guid.Empty) { Console.WriteLine("No joystick/Gamepad found."); Console.ReadKey(); Environment.Exit(1); } // Instantiate the joystick var joystick = new Joystick(directInput, joystickGuid); Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid); // Query all suported ForceFeedback effects var allEffects = joystick.GetEffects(); foreach (var effectInfo in allEffects) { Console.WriteLine("Effect available {0}", effectInfo.Name); } // Set BufferSize in order to use buffered data. joystick.Properties.BufferSize = 128; // Acquire the joystick joystick.Acquire(); const int stop = 32511; // Poll events from joystick while (true) { joystick.Poll(); var datas = joystick.GetBufferedData(); foreach (var state in datas) { if (state.Offset.ToString() == "X" && state.Value > stop) { MoveRobot("MOVE", "R"); Console.WriteLine("Kanan"); } else if (state.Offset.ToString() == "X" && state.Value < stop) { MoveRobot("MOVE", "L"); Console.WriteLine("Kiri"); } else if (state.Offset.ToString() == "Y" && state.Value < stop) { MoveRobot("MOVE", "F"); Console.WriteLine("Maju"); } else if (state.Offset.ToString() == "Y" && state.Value > stop) { MoveRobot("MOVE", "B"); Console.WriteLine("Mundur"); } else { MoveRobot("MOVE", "S"); Console.WriteLine("Stop"); } } } }
void ShowDeviceInfo(Joystick device) { if (device == null) { // clean everything here. SetValue(DeviceProductNameTextBox, ""); SetValue(DeviceProductGuidTextBox, ""); SetValue(DeviceInstanceGuidTextBox, ""); DiCapFfStateTextBox.Text = string.Empty; DiCapAxesTextBox.Text = string.Empty; DiCapButtonsTextBox.Text = string.Empty; DiCapDPadsTextBox.Text = string.Empty; DiEffectsTable.Rows.Clear(); return; } lock (MainForm.XInputLock) { var isLoaded = XInput.IsLoaded; if (isLoaded) XInput.FreeLibrary(); device.Unacquire(); device.SetCooperativeLevel(MainForm.Current, CooperativeLevel.Foreground | CooperativeLevel.Exclusive); effects = new List<EffectInfo>(); try { device.Acquire(); var forceFeedback = device.Capabilities.Flags.HasFlag(DeviceFlags.ForceFeedback); forceFeedbackState = forceFeedback ? "YES" : "NO"; effects = device.GetEffects(EffectType.All); } catch (Exception) { forceFeedbackState = "ERROR"; } DiEffectsTable.Rows.Clear(); foreach (var eff in effects) { DiEffectsTable.Rows.Add(new object[]{ eff.Name, ((EffectParameterFlags)eff.StaticParameters).ToString(), ((EffectParameterFlags)eff.DynamicParameters).ToString() }); } device.Unacquire(); device.SetCooperativeLevel(MainForm.Current, CooperativeLevel.Background | CooperativeLevel.NonExclusive); if (isLoaded) { Exception error; XInput.ReLoadLibrary(XInput.LibraryName, out error); } } DiCapFfStateTextBox.Text = forceFeedbackState; DiCapButtonsTextBox.Text = device.Capabilities.ButtonCount.ToString(); DiCapDPadsTextBox.Text = device.Capabilities.PovCount.ToString(); var objects = device.GetObjects(DeviceObjectTypeFlags.All).OrderBy(x => x.Offset).ToArray(); DiObjectsTable.Rows.Clear(); var og = typeof(SharpDX.DirectInput.ObjectGuid); var guidFileds = og.GetFields().Where(x => x.FieldType == typeof(Guid)); List<Guid> guids = guidFileds.Select(x => (Guid)x.GetValue(og)).ToList(); List<string> names = guidFileds.Select(x => x.Name).ToList(); foreach (var o in objects) { DiObjectsTable.Rows.Add(new object[]{ o.Offset, o.ObjectId.InstanceNumber, o.Usage, o.Name, o.Aspect, guids.Contains(o.ObjectType) ? names[guids.IndexOf(o.ObjectType)] : o.ObjectType.ToString(), o.ObjectId.Flags, }); } var actuators = objects.Where(x => x.ObjectId.Flags.HasFlag(DeviceObjectTypeFlags.ForceFeedbackActuator)); ActuatorsTextBox.Text = actuators.Count().ToString(); var di = device.Information; var slidersCount = objects.Where(x => x.ObjectType.Equals(SharpDX.DirectInput.ObjectGuid.Slider)).Count(); DiCapAxesTextBox.Text = (device.Capabilities.AxeCount - slidersCount).ToString(); SlidersTextBox.Text = slidersCount.ToString(); // Update PID and VID always so they wont be overwritten by load settings. short vid = BitConverter.ToInt16(di.ProductGuid.ToByteArray(), 0); short pid = BitConverter.ToInt16(di.ProductGuid.ToByteArray(), 2); SetValue(DeviceVidTextBox, "0x{0}", vid.ToString("X4")); SetValue(DevicePidTextBox, "0x{0}", pid.ToString("X4")); SetValue(DeviceProductNameTextBox, di.ProductName); SetValue(DeviceProductGuidTextBox, di.ProductGuid.ToString()); SetValue(DeviceInstanceGuidTextBox, di.InstanceGuid.ToString()); SetValue(DeviceTypeTextBox, di.Type.ToString()); }
private void HandleJoystick() { if (joystick.Acquire().IsFailure) { return; } if (joystick.Poll().IsFailure) { return; } try { joystick.GetCurrentState(ref joystickState); if (joystickState.X < 0x3FFF) { if (!joyLeftPressed) { InputEvent(EmuKeys.JoyLeft, true); } joyLeftPressed = true; } else { if (joyLeftPressed) { InputEvent(EmuKeys.JoyLeft, false); } joyLeftPressed = false; } if (joystickState.X > 0xBFFF) { if (!joyRightPressed) { InputEvent(EmuKeys.JoyRight, true); } joyRightPressed = true; } else { if (joyRightPressed) { InputEvent(EmuKeys.JoyRight, false); } joyRightPressed = false; } if (joystickState.Y < 0x3FFF) { if (!joyUpPressed) { InputEvent(EmuKeys.JoyUp, true); } joyUpPressed = true; } else { if (joyUpPressed) { InputEvent(EmuKeys.JoyUp, false); } joyUpPressed = false; } if (joystickState.Y > 0xBFFF) { if (!joyDownPressed) { InputEvent(EmuKeys.JoyDown, true); } joyDownPressed = true; } else { if (joyDownPressed) { InputEvent(EmuKeys.JoyDown, false); } joyDownPressed = false; } bool[] buttons = joystickState.GetButtons(); for (int i = 0; i < buttons.Length && i < 10; i++) { if (buttons[i] != currentJoyButtons[i]) { switch (i) { case 0: InputEvent(EmuKeys.Joy1, buttons[i]); break; case 1: InputEvent(EmuKeys.Joy2, buttons[i]); break; case 2: InputEvent(EmuKeys.Joy3, buttons[i]); break; case 3: InputEvent(EmuKeys.Joy4, buttons[i]); break; case 4: InputEvent(EmuKeys.Joy5, buttons[i]); break; case 5: InputEvent(EmuKeys.Joy6, buttons[i]); break; case 6: InputEvent(EmuKeys.Joy7, buttons[i]); break; case 7: InputEvent(EmuKeys.Joy8, buttons[i]); break; case 8: InputEvent(EmuKeys.Joy9, buttons[i]); break; case 9: InputEvent(EmuKeys.Joy10, buttons[i]); break; } currentJoyButtons[i] = buttons[i]; } } } catch { joystick.Acquire(); } }
public int Init(DirectInput pdinput, DeviceInstance di) { dinput = pdinput; int min = 0; int max = 65535; trackBarX.Minimum = trackBarY.Minimum = trackBarZ.Minimum = trackBarRX.Minimum = trackBarRY.Minimum = trackBarRZ.Minimum = trackBarS1.Minimum = trackBarS2.Minimum = min; trackBarX.Maximum = trackBarY.Maximum = trackBarZ.Maximum = trackBarRX.Maximum = trackBarRY.Maximum = trackBarRZ.Maximum = trackBarS1.Maximum = trackBarS2.Maximum = max; trackBarX.Visible = trackBarY.Visible = trackBarZ.Visible = trackBarRX.Visible = trackBarRY.Visible = trackBarRZ.Visible = trackBarS1.Visible = trackBarS2.Visible = false; labelX.Visible = labelY.Visible = labelZ.Visible = labelRX.Visible = labelRY.Visible = labelRZ.Visible = labelS1.Visible = labelS2.Visible = false; povBox1.Visible = povBox2.Visible = false; try { stickname = di.InstanceName.RemoveNuls(); stick = new SharpDX.DirectInput.Joystick(dinput, di.InstanceGuid); stick.Acquire(); Capabilities c = stick.Capabilities; povcount = c.PovCount; butcount = c.ButtonCount; rb = new RadioButton[butcount]; slidercount = 0; DeviceProperties p = stick.Properties; groupBox1.Text = stickname.Substring(0, di.InstanceName.IndexOf('\0')) + " : " + p.VendorId.ToString("X4") + p.ProductId.ToString("X4"); System.Diagnostics.Debug.WriteLine(" ax {0} but {1} pov {2} vid {3:X} pid {4:X}", c.AxeCount, c.ButtonCount, c.PovCount, p.VendorId, p.ProductId); if (!stickname.Contains("CH")) { // return 0; } foreach (DeviceObjectInstance deviceObject in stick.GetObjects()) { if ((deviceObject.ObjectId.Flags & DeviceObjectTypeFlags.Axis) != 0) { System.Guid guid = deviceObject.ObjectType; System.Diagnostics.Debug.WriteLine(" {0} {1} {2} {3} {4}", deviceObject.Name.RemoveNuls(), deviceObject.UsagePage, deviceObject.Usage, deviceObject.Offset, guid.ToString().RemoveNuls()); if (guid == ObjectGuid.XAxis) { labelX.Visible = trackBarX.Visible = true; } else if (guid == ObjectGuid.YAxis) { labelY.Visible = trackBarY.Visible = true; } else if (guid == ObjectGuid.ZAxis) { labelZ.Visible = trackBarZ.Visible = true; } else if (guid == ObjectGuid.RxAxis) { labelRX.Visible = trackBarRX.Visible = true; } else if (guid == ObjectGuid.RyAxis) { labelRY.Visible = trackBarRY.Visible = true; } else if (guid == ObjectGuid.RzAxis) { labelRZ.Visible = trackBarRZ.Visible = true; } else if (guid == ObjectGuid.Slider) { if (slidercount == 0) { labelS1.Visible = trackBarS1.Visible = true; // labelS2.Visible = trackBarS2.Visible = true; } else if (slidercount == 1) { labelS2.Visible = trackBarS2.Visible = true; } slidercount++; // 3 on shown as numbers } ObjectProperties o = stick.GetObjectPropertiesById(deviceObject.ObjectId); //System.Diagnostics.Debug.WriteLine(" L" + o.LowerRange + " U" + o.UpperRange + " G" + o.Granularity + " D" + o.DeadZone + " Il" + o.LogicalRange.Minimum + " Iu" + o.LogicalRange.Maximum); o.Range = new InputRange(min, max); } } // compress up the tracks int diff = labelRX.Top - labelX.Top; if (labelX.Visible == false) // move RX up to X if possible { labelRX.Top -= diff; trackBarRX.Top -= diff; } if (labelY.Visible == false) { labelRY.Top -= diff; trackBarRY.Top -= diff; } if (labelZ.Visible == false) { labelRZ.Top -= diff; trackBarRZ.Top -= diff; } // if RZ in same place, but S1 is missing, and there is nothing else on RZ line else if (labelS1.Visible == false && labelRZ.Visible == true && labelRX.Visible == false && labelRY.Visible == false && labelS2.Visible == false) { labelRZ.Location = labelS1.Location; trackBarRZ.Location = trackBarS1.Location; } List <Control> tracks = new List <Control>() { trackBarX, trackBarY, trackBarZ, trackBarS1, trackBarRX, trackBarRY, trackBarRZ, trackBarS2 }; int maxtrackvisible = tracks.Where(w => w.Visible).Select(x => x.Bottom).Max(); // find bottom of all tracks povBox1.Top = povBox2.Top = maxtrackvisible + 4; if (povcount > 0) { povstate = new int[povcount]; povBox1.Visible = true; } if (povcount > 1) { povBox2.Visible = true; } int hbase = (povBox1.Visible || povBox2.Visible) ? povBox1.Bottom + 4 : maxtrackvisible + 4; for (int i = 0; i < butcount; i++) { Panel p1 = new Panel(); p1.Location = new Point((i % 16) * 50 + 5, hbase + 20 * (i / 16)); p1.Size = new Size(50, 20); RadioButton r = new RadioButton(); r.Location = new Point(1, 5); r.AutoSize = true; r.Size = new Size(85, 18); r.Text = "B" + (i + 1); p1.Controls.Add(r); rb[i] = r; groupBox1.Controls.Add(p1); } return(hbase + 16 + 20 * ((butcount + 15) / 16)); // size of UC.. include space for groupbox } catch { return(0); } }
public void InitDevices() { Logger.Info("Starting Device Search. Expand Search: " + (_globalSettings.GetClientSettingBool(GlobalSettingsKeys.ExpandControls))); var deviceInstances = _directInput.GetDevices(); foreach (var deviceInstance in deviceInstances) { //Workaround for Bad Devices that pretend to be joysticks if (!IsBlackListed(deviceInstance.ProductGuid)) { Logger.Info("Found Device ID:" + deviceInstance.ProductGuid + " " + deviceInstance.ProductName.Trim().Replace("\0", "") + " Usage: " + deviceInstance.UsagePage + " Type: " + deviceInstance.Type); if (_inputDevices.ContainsKey(deviceInstance.InstanceGuid)) { Logger.Info("Already have device:" + deviceInstance.ProductGuid + " " + deviceInstance.ProductName.Trim().Replace("\0", "")); } else { if (deviceInstance.Type == DeviceType.Keyboard) { Logger.Info("Adding Device ID:" + deviceInstance.ProductGuid + " " + deviceInstance.ProductName.Trim().Replace("\0", "")); var device = new Keyboard(_directInput); device.SetCooperativeLevel(WindowHelper.Handle, CooperativeLevel.Background | CooperativeLevel.NonExclusive); device.Acquire(); _inputDevices.Add(deviceInstance.InstanceGuid, device); } else if (deviceInstance.Type == DeviceType.Mouse) { Logger.Info("Adding Device ID:" + deviceInstance.ProductGuid + " " + deviceInstance.ProductName.Trim().Replace("\0", "")); var device = new Mouse(_directInput); device.SetCooperativeLevel(WindowHelper.Handle, CooperativeLevel.Background | CooperativeLevel.NonExclusive); device.Acquire(); _inputDevices.Add(deviceInstance.InstanceGuid, device); } else if (((deviceInstance.Type >= DeviceType.Joystick) && (deviceInstance.Type <= DeviceType.FirstPerson)) || IsWhiteListed(deviceInstance.ProductGuid)) { var device = new Joystick(_directInput, deviceInstance.InstanceGuid); Logger.Info("Adding ID:" + deviceInstance.ProductGuid + " " + deviceInstance.ProductName.Trim().Replace("\0", "")); device.SetCooperativeLevel(WindowHelper.Handle, CooperativeLevel.Background | CooperativeLevel.NonExclusive); device.Acquire(); _inputDevices.Add(deviceInstance.InstanceGuid, device); } else if (GlobalSettingsStore.Instance.GetClientSettingBool(GlobalSettingsKeys.ExpandControls)) { Logger.Info("Adding (Expanded Devices) ID:" + deviceInstance.ProductGuid + " " + deviceInstance.ProductName.Trim().Replace("\0", "")); var device = new Joystick(_directInput, deviceInstance.InstanceGuid); device.SetCooperativeLevel(WindowHelper.Handle, CooperativeLevel.Background | CooperativeLevel.NonExclusive); device.Acquire(); _inputDevices.Add(deviceInstance.InstanceGuid, device); Logger.Info("Added (Expanded Device) ID:" + deviceInstance.ProductGuid + " " + deviceInstance.ProductName.Trim().Replace("\0", "")); } } } else { Logger.Info("Found but ignoring blacklist device " + deviceInstance.ProductGuid + " Instance: " + deviceInstance.InstanceGuid + " " + deviceInstance.ProductName.Trim().Replace("\0", "") + " Type: " + deviceInstance.Type); } } }
// Rescan joysticks. This can be called after a new joystick has been // plugged in, or just on spec that one might have. We'll run the system // discovery scan again, and add new entries to our internal list for any // joysticks not already in the list. public static void Rescan() { // log scans for debugging purposes? bool log = false; if (log) { Log.Info("Scanning for USB devices"); } // get the list of attached joysticks var devices = directInput.GetDevices(DeviceClass.All, DeviceEnumerationFlags.AttachedOnly); int unitNo = joysticks.Count + 1; foreach (var dev in devices) { // if this device is already in our list, there's nothing to do if (joysticks.ContainsKey(dev.InstanceGuid)) { continue; } // check USB usage to see if it's a joystick bool isJoystick = (dev.UsagePage == SharpDX.Multimedia.UsagePage.Generic && dev.Usage == SharpDX.Multimedia.UsageId.GenericJoystick); // check if it's a gamepad bool isGamepad = (dev.UsagePage == SharpDX.Multimedia.UsagePage.Generic && dev.Usage == SharpDX.Multimedia.UsageId.GenericGamepad); // note the product name for logging purposes String productName = dev.ProductName.TrimEnd('\0'); // log it if desired if (log) { Log.Info((isJoystick ? " Found joystick: " : isGamepad ? " Found gamepad: " : " Found non-joystick device: ") + productName + ", DirectInput type=" + dev.Type + "/" + dev.Subtype + ", USB usage=" + (int)dev.UsagePage + "." + (int)dev.Usage); } // skip devices that aren't joysticks or gamepads if (!isJoystick && !isGamepad) { continue; } // initialize it try { // create the instance and add it to our list Joystick js = new Joystick(directInput, dev.InstanceGuid); JoystickDev jsdev = new JoystickDev(unitNo++, js, dev.InstanceGuid); joysticks[dev.InstanceGuid] = jsdev; // request non-exclusive background access js.SetCooperativeLevel(win.Handle, CooperativeLevel.NonExclusive | CooperativeLevel.Background); // Set up an input monitor thread for the joystick. Note that the // DX API requires this to be done before we call 'Acquire'. js.SetNotification(jsdev.hWait); // connect to the joystick js.Acquire(); // Start the monitor thread. Note that we have to do this after // calling 'Acquire', since the thread will want to read state. jsdev.thread = new Thread(jsdev.JoystickThreadMain); jsdev.thread.Start(); } catch (Exception ex) { Log.Error(" !!! Error initializing joystick device " + productName + ": " + ex.Message); } } }
public JoystickHandler() { List <DeviceInstance> directInputList = new List <DeviceInstance>(); DirectInput directInput = new DirectInput(); directInputList.AddRange(directInput.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly)); if (directInputList.Count == 0) { Console.WriteLine("No Devices Found!"); Console.ReadKey(); return; } Console.WriteLine("Devices Found"); int i = 0; foreach (DeviceInstance device in directInputList) { Console.WriteLine(i + ": " + device.InstanceName); i++; } string input = Console.ReadLine(); if (!int.TryParse(input, out i)) { switch (input) { case ("options"): HandleSettings(); Settings.Default.Save(); break; default: break; } } // Startup Complete Joystick ActiveJoystick = new Joystick(directInput, directInputList[i].InstanceGuid); foreach (DeviceObjectInstance doi in ActiveJoystick.GetObjects(ObjectDeviceType.Axis)) { ActiveJoystick.GetObjectPropertiesById((int)doi.ObjectType).SetRange(-5000, 5000); } ActiveJoystick.Properties.AxisMode = DeviceAxisMode.Absolute; ActiveJoystick.Acquire(); JoystickState ActiveJoystickState = ActiveJoystick.GetCurrentState(); int screenWidth = InternalGetSystemMetrics(0); int screenHeight = InternalGetSystemMetrics(1); int to_x = screenWidth / 2; int to_y = screenHeight / 2; int mic_x = (int)Math.Round(to_x * 65536.0 / screenWidth); int mic_y = (int)Math.Round(to_y * 65536.0 / screenHeight); int[] defaultDeviceState = { ActiveJoystickState.X, ActiveJoystickState.Y, ActiveJoystickState.RotationZ }; INPUT[] MouseInputs = new INPUT[1]; InputData KeyboardInput = new InputData(); // Init Buttons int buttonCount = ActiveJoystick.Capabilities.ButtonCount; List <JoystickButton> joystickButtons = new List <JoystickButton>(); int o = 0; for (o = 0; i < buttonCount; i++) { joystickButtons.Add(new JoystickButton() { buttonName = "Button" + i, buttonState = false }); } bool[] buttonState = new bool[o]; while (true) { loop: Thread.Sleep(100 / refreshRate); ActiveJoystickState = ActiveJoystick.GetCurrentState(); buttonState = ActiveJoystickState.GetButtons(); // poll buttons int e = 0; foreach (JoystickButton button in joystickButtons) { button.buttonState = buttonState[e]; e++; } if (joystickButtons[0].buttonState) { if (MouseInputs[0].U.mi.dwFlags != MOUSEEVENTF.LEFTDOWN) { MouseInputs[0].U.mi.dwFlags = MOUSEEVENTF.MOVE | MOUSEEVENTF.LEFTDOWN; } else { MouseInputs[0].U.mi.dwFlags = MOUSEEVENTF.MOVE; } } else { if (MouseInputs[0].U.mi.dwFlags > MOUSEEVENTF.LEFTDOWN) { MouseInputs[0].U.mi.dwFlags = MOUSEEVENTF.MOVE | MOUSEEVENTF.LEFTUP; } else { MouseInputs[0].U.mi.dwFlags = MOUSEEVENTF.MOVE; } } if (ActiveJoystick.Poll().IsFailure || ActiveJoystick.GetCurrentState(ref ActiveJoystickState).IsFailure) { Console.WriteLine("Polling Failed"); goto loop; } MouseInputs[0].U.mi.dx = (int)((ActiveJoystickState.X - defaultDeviceState[0]) * sensitivity * factor) * (Settings.Default.InvertX ? -1 : 1); MouseInputs[0].U.mi.dy = (int)((ActiveJoystickState.Y - defaultDeviceState[1]) * sensitivity * factor) * (Settings.Default.InvertY ? -1 : 1); MouseInputs[0].type = 0; SendInput(1, MouseInputs, INPUT.Size); if ((ActiveJoystick.GetCurrentState().RotationZ < 100 && ActiveJoystick.GetCurrentState().RotationZ > -100) && KeyboardInput.KEYEVENTF != KEYEVENTF.KEYUP) { KeyboardInput.KEYEVENTF = KEYEVENTF.KEYUP; } if ((ActiveJoystick.GetCurrentState().RotationZ > defaultDeviceState[2] + 100) && KeyboardInput.ScanCodeShort != ScanCodeShort.KEY_D) { KeyboardInput.KEYEVENTF = 0; KeyboardInput.ScanCodeShort = ScanCodeShort.KEY_D; } if ((ActiveJoystick.GetCurrentState().RotationZ < defaultDeviceState[2] - 100) && KeyboardInput.ScanCodeShort != ScanCodeShort.KEY_A) { KeyboardInput.KEYEVENTF = 0; KeyboardInput.ScanCodeShort = ScanCodeShort.KEY_A; } SendInput(1, GetKeyInput(KeyboardInput.KEYEVENTF, KeyboardInput.ScanCodeShort), INPUT.Size); } }
private void Awake() { if (trap == false) { speed = PlayerPrefs.GetFloat("ZombieSurvivalPlayerSpeed", speed); bltDmg = PlayerPrefs.GetFloat("ZombieSurvivalPlayerBulletDamage", bltDmg); atkSpd = PlayerPrefs.GetFloat("ZombieSurvivalPlayerBulletReload", atkSpd); bltSpd = PlayerPrefs.GetFloat("ZombieSurvivalPlayerBulletSpeed", bltSpd); dashSpeed = PlayerPrefs.GetFloat("ZombieSurvivalPlayerDashSpeed", dashSpeed); } else { speed = PlayerPrefs.GetFloat("ZombieInfectionPlayerSpeed", speed); bltDmg = PlayerPrefs.GetFloat("ZombieInfectionPlayerBulletDamage", bltDmg); atkSpd = PlayerPrefs.GetFloat("ZombieInfectionPlayerBulletReload", atkSpd); bltSpd = PlayerPrefs.GetFloat("ZombieInfectionPlayerBulletSpeed", bltSpd); zombieSpeed = PlayerPrefs.GetFloat("ZombieInfectionZombieSpeed", zombieSpeed); zombieHealth = PlayerPrefs.GetFloat("ZombieInfectionZombieHealth", zombieHealth); } Invoke("Times", 1f); ZombieSurvival_player[] players = FindObjectsOfType <ZombieSurvival_player>(); deathVfx = GameObject.Find("playerDeath"); bullet = GameObject.Find("bullet"); if (trap) { trapObj = GameObject.Find("beartrap1"); zombie = GameObject.Find("Zombie"); } foreach (ZombieSurvival_player player in players) { if (bot) { if (player.bot == true) { Physics2D.IgnoreCollision(GetComponent <CircleCollider2D>(), player.GetComponent <CircleCollider2D>()); } else { Physics2D.IgnoreCollision(GetComponent <CircleCollider2D>(), player.GetComponent <BoxCollider2D>()); } } else { if (player.bot == true) { Physics2D.IgnoreCollision(GetComponent <BoxCollider2D>(), player.GetComponent <CircleCollider2D>()); } else { Physics2D.IgnoreCollision(GetComponent <BoxCollider2D>(), player.GetComponent <BoxCollider2D>()); } } } if (FindObjectOfType <PlayerData>().bots[playerNumber] == true && bot == false) { GameObject botz = Instantiate(botObj); botz.transform.position = transform.position; botz.GetComponent <ZombieSurvival_player>().difficulty = FindObjectOfType <PlayerData>().botDifficulties[playerNumber]; botz.GetComponent <ZombieSurvival_player>().playerNumber = playerNumber; botz.GetComponent <ZombieSurvival_player>().team = team; botz.GetComponent <ZombieSurvival_player>().trap = trap; botz.GetComponent <ZombieSurvival_player>().infection = infection; FindObjectOfType <SpawnPlayers>().players.Add(botz); FindObjectOfType <SpawnPlayers>().players.Remove(gameObject); botz.GetComponent <ZombieSurvival_player>().Enable(); Debug.Log("death1" + ' ' + playerNumber); Destroy(gameObject); } else if (!bot) { joystick = FindObjectOfType <PlayerData>().controllers[playerNumber]; if (joystick == null || FindObjectOfType <PlayerData>().pollControllers[playerNumber] || FindObjectOfType <PlayerData>().players.Contains(playerNumber) == false) { FindObjectOfType <SpawnPlayers>().players.Remove(gameObject); Destroy(gameObject); } else { if (joystick.Information.Type == SharpDX.DirectInput.DeviceType.Keyboard) { keyboard = true; } if (playerNumber <= 2) { if (playerNumber == 1) { dreapta = 31; stanga = 29; jos = 30; sus = 16; } else { dreapta = 107; stanga = 106; jos = 109; sus = 104; } } button1 = FindObjectOfType <PlayerData>().button1[playerNumber]; button2 = FindObjectOfType <PlayerData>().button2[playerNumber]; joystick.Acquire(); } tutorialAbleToMove = false; GetComponent <AudioSource>().clip = attack; bool ok = false; foreach (int player in FindObjectOfType <PlayerData>().players) { if (playerNumber == player) { ok = true; spriteColor1.color = FindObjectOfType <PlayerData>().color1[playerNumber]; spriteColor2.color = FindObjectOfType <PlayerData>().color2[playerNumber]; } } if (ok == false) { FindObjectOfType <SpawnPlayers>().players.Remove(gameObject); Destroy(gameObject); } else { teamColor.text = FindObjectOfType <PlayerData>().playerNames[playerNumber]; if (FindObjectOfType <PlayerData>().teams == true) { team = FindObjectOfType <PlayerData>().playerTeams[playerNumber]; if (team == 0) { teamColor.color = new Color32(0, 175, 255, 255); } else { teamColor.color = new Color32(255, 0, 0, 255); } } else { teamColor.color = new Color32(255, 255, 255, 255); } } Invoke("StartMoving", 5.5f); } }
public DeviceReport GetInputDeviceReport(DeviceDescriptor deviceDescriptor, Guid deviceGuid) { var joystick = new Joystick(DiInstance, deviceGuid); joystick.Acquire(); var deviceReport = new DeviceReport { DeviceDescriptor = deviceDescriptor, DeviceName = $"{joystick.Information.ProductName}{(deviceDescriptor.DeviceInstance > 0 ? $" # {deviceDescriptor.DeviceInstance + 1}" : "")}", HidPath = joystick.Properties.InterfacePath }; // ----- Axes ----- if (joystick.Capabilities.AxeCount > 0) { var axisInfo = new DeviceReportNode { Title = "Axes" }; // SharpDX tells us how many axes there are, but not *which* axes. // Enumerate all possible DI axes and check to see if this stick has each axis for (var i = 0; i < Utilities.OffsetsByType[BindingType.Axis].Count; i++) { try { var offset = Utilities.OffsetsByType[BindingType.Axis][i]; // this will throw if invalid offset var deviceInfo = joystick.GetObjectInfoByName(offset // this bit will throw if the stick does not have that axis .ToString()); axisInfo.Bindings.Add(GetInputBindingReport(deviceDescriptor, new BindingDescriptor { //Index = i, Index = (int)offset, //Name = axisNames[i], Type = BindingType.Axis })); } catch { // axis does not exist } } deviceReport.Nodes.Add(axisInfo); // ----- Buttons ----- var length = joystick.Capabilities.ButtonCount; if (length > 0) { var buttonInfo = new DeviceReportNode { Title = "Buttons" }; for (var btn = 0; btn < length; btn++) { buttonInfo.Bindings.Add(GetInputBindingReport(deviceDescriptor, new BindingDescriptor { //Index = btn, Index = (int)Utilities.OffsetsByType[BindingType.Button][btn], Type = BindingType.Button })); } deviceReport.Nodes.Add(buttonInfo); } // ----- POVs ----- var povCount = joystick.Capabilities.PovCount; if (povCount > 0) { var povsInfo = new DeviceReportNode { Title = "POVs" }; for (var p = 0; p < povCount; p++) { var povInfo = new DeviceReportNode { Title = "POV #" + (p + 1), Bindings = PovBindingInfos[p] }; povsInfo.Nodes.Add(povInfo); } deviceReport.Nodes.Add(povsInfo); } } return(deviceReport); }
void ShowDeviceInfo(Joystick device, DeviceInfo dInfo) { if (device == null) { // clean everything here. SetValue(DeviceProductNameTextBox, ""); SetValue(DeviceVendorNameTextBox, ""); SetValue(DeviceProductGuidTextBox, ""); SetValue(DeviceInstanceGuidTextBox, ""); DiCapFfStateTextBox.Text = string.Empty; DiCapAxesTextBox.Text = string.Empty; DiCapButtonsTextBox.Text = string.Empty; DiCapDPadsTextBox.Text = string.Empty; DiEffectsTable.Rows.Clear(); return; } lock (XInput.XInputLock) { var isLoaded = XInput.IsLoaded; if (isLoaded) { XInput.FreeLibrary(); } device.Unacquire(); device.SetCooperativeLevel(MainForm.Current.Handle, CooperativeLevel.Foreground | CooperativeLevel.Exclusive); effects = new List <EffectInfo>(); try { device.Acquire(); var forceFeedback = device.Capabilities.Flags.HasFlag(DeviceFlags.ForceFeedback); forceFeedbackState = forceFeedback ? "YES" : "NO"; effects = device.GetEffects(EffectType.All); } catch (Exception) { forceFeedbackState = "ERROR"; } DiEffectsTable.Rows.Clear(); foreach (var eff in effects) { DiEffectsTable.Rows.Add(new object[] { eff.Name, ((EffectParameterFlags)eff.StaticParameters).ToString(), ((EffectParameterFlags)eff.DynamicParameters).ToString() }); } device.Unacquire(); device.SetCooperativeLevel(MainForm.Current.Handle, CooperativeLevel.Background | CooperativeLevel.NonExclusive); if (isLoaded) { Exception error; XInput.ReLoadLibrary(XInput.LibraryName, out error); } } DiCapFfStateTextBox.Text = forceFeedbackState; DiCapButtonsTextBox.Text = device.Capabilities.ButtonCount.ToString(); DiCapDPadsTextBox.Text = device.Capabilities.PovCount.ToString(); var objects = AppHelper.GetDeviceObjects(device); DiObjectsDataGridView.DataSource = objects; var actuators = objects.Where(x => x.Flags.HasFlag(DeviceObjectTypeFlags.ForceFeedbackActuator)); ActuatorsTextBox.Text = actuators.Count().ToString(); var di = device.Information; var slidersCount = objects.Where(x => x.Type.Equals(SharpDX.DirectInput.ObjectGuid.Slider)).Count(); DiCapAxesTextBox.Text = (device.Capabilities.AxeCount - slidersCount).ToString(); SlidersTextBox.Text = slidersCount.ToString(); // Update PID and VID always so they wont be overwritten by load settings. short vid = BitConverter.ToInt16(di.ProductGuid.ToByteArray(), 0); short pid = BitConverter.ToInt16(di.ProductGuid.ToByteArray(), 2); SetValue(DeviceVidTextBox, "0x{0}", vid.ToString("X4")); SetValue(DevicePidTextBox, "0x{0}", pid.ToString("X4")); SetValue(DeviceProductNameTextBox, di.ProductName); SetValue(DeviceVendorNameTextBox, dInfo == null ? "" : dInfo.Manufacturer); SetValue(DeviceProductGuidTextBox, di.ProductGuid.ToString()); SetValue(DeviceInstanceGuidTextBox, di.InstanceGuid.ToString()); SetValue(DeviceTypeTextBox, di.Type.ToString()); }
/// <summary> /// Initializes a joystick device using the specified global unique identifier. /// </summary> /// <param name="handle">A pointer to the application's master form.</param> /// <param name="g">The GUID of the device to initialize.</param> public static void DInputInit(IntPtr handle, Guid g) { if (JSDevice != null) { JSDevice.Unacquire(); JSDevice = null; } JSDevice = new Joystick(input, g); int xAxisOffset = 0, yAxisOffset = 0; int nextOffset = 0; // JSDevice.Properties.AutoCenter = true; foreach (DeviceObjectInstance d in JSDevice.GetObjects()) { if ((d.ObjectId.Flags & DeviceObjectTypeFlags.ForceFeedbackActuator) == DeviceObjectTypeFlags.ForceFeedbackActuator) { if (nextOffset == 0) { xAxisOffset = d.Offset; } else { yAxisOffset = d.Offset; } nextOffset++; } if (d.ObjectType == ObjectGuid.XAxis) { JSDevice.GetObjectPropertiesById( d.ObjectId).Range = new InputRange(-5, 5); JSDevice.GetObjectPropertiesById( d.ObjectId).DeadZone = 1000; } if (d.ObjectType == ObjectGuid.YAxis) { JSDevice.GetObjectPropertiesById(d.ObjectId).Range = new InputRange(-9, 9); JSDevice.GetObjectPropertiesById( d.ObjectId).DeadZone = 1000; } if (d.ObjectType == ObjectGuid.Slider) { JSDevice.GetObjectPropertiesById( d.ObjectId).Range = new InputRange(0, 11); JSSliderId = d.ObjectId; useSlider = true; } if (d.ObjectType == ObjectGuid.ZAxis) { JSDevice.GetObjectPropertiesById( d.ObjectId).Range = new InputRange(0, 11); jsZId = d.ObjectId; useZ = true; } if (d.ObjectType == ObjectGuid.RzAxis) { JSDevice.GetObjectPropertiesById( d.ObjectId).Range = new InputRange(-5, 5); } } //for if (useSlider && useZ) { useSlider = false; } JSDevice.SetCooperativeLevel(handle, CooperativeLevel.Background | CooperativeLevel.Exclusive); JSDevice.Acquire(); updateJSState(); TheJSButtons = JSState.Buttons; if (nextOffset > 0) { if (!dInputInitFD(JSDevice, xAxisOffset, yAxisOffset, nextOffset)) { OggBuffer error = DSound.loadOgg(DSound.SoundPath + "\\ffbd.ogg"); error.play(); while (error.isPlaying()) { Thread.Sleep(10); } error.stopOgg(); error = null; forceFeedbackEnabled = false; } else { forceFeedbackEnabled = true; } } }
private bool AcquireController() { _controller.SetCooperativeLevel(_handle, CooperativeLevel.Exclusive | CooperativeLevel.Background); _controller.Acquire(); return(true); }
public void Acquire() { this.joystick = new Joystick(this.DirectInput, this.InstanceGuid); joystick.Properties.BufferSize = this.BufferSize; joystick.Acquire(); }
void ShowDeviceInfo(Joystick device, UserDevice dInfo) { if (device == null) { // clean everything here. AppHelper.SetText(DeviceProductNameTextBox, ""); AppHelper.SetText(DeviceVendorNameTextBox, ""); AppHelper.SetText(DeviceProductGuidTextBox, ""); AppHelper.SetText(DeviceInstanceGuidTextBox, ""); AppHelper.SetText(DiCapFfStateTextBox, ""); AppHelper.SetText(DiCapAxesTextBox, ""); AppHelper.SetText(DiCapButtonsTextBox, ""); AppHelper.SetText(DiCapDPadsTextBox, ""); if (DiEffectsTable.Rows.Count > 0) { DiEffectsTable.Rows.Clear(); } return; } lock (MainForm.XInputLock) { var isLoaded = XInput.IsLoaded; if (isLoaded) { XInput.FreeLibrary(); } device.Unacquire(); device.SetCooperativeLevel(MainForm.Current, CooperativeLevel.Foreground | CooperativeLevel.Exclusive); effects = new List <EffectInfo>(); try { device.Acquire(); var forceFeedback = device.Capabilities.Flags.HasFlag(DeviceFlags.ForceFeedback); forceFeedbackState = forceFeedback ? "YES" : "NO"; effects = device.GetEffects(EffectType.All); } catch (Exception) { forceFeedbackState = "ERROR"; } DiEffectsTable.Rows.Clear(); foreach (var eff in effects) { DiEffectsTable.Rows.Add(new object[] { eff.Name, ((EffectParameterFlags)eff.StaticParameters).ToString(), ((EffectParameterFlags)eff.DynamicParameters).ToString() }); } device.Unacquire(); device.SetCooperativeLevel(MainForm.Current, CooperativeLevel.Background | CooperativeLevel.NonExclusive); if (isLoaded) { Exception error; XInput.ReLoadLibrary(XInput.LibraryName, out error); } } AppHelper.SetText(DiCapFfStateTextBox, forceFeedbackState); AppHelper.SetText(DiCapButtonsTextBox, device.Capabilities.ButtonCount.ToString()); AppHelper.SetText(DiCapDPadsTextBox, device.Capabilities.PovCount.ToString()); var objects = AppHelper.GetDeviceObjects(device); DiObjectsDataGridView.DataSource = objects; var actuators = objects.Where(x => x.Flags.HasFlag(DeviceObjectTypeFlags.ForceFeedbackActuator)); AppHelper.SetText(ActuatorsTextBox, actuators.Count().ToString()); var di = device.Information; var slidersCount = objects.Where(x => x.GuidValue.Equals(SharpDX.DirectInput.ObjectGuid.Slider)).Count(); // https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.dijoystate2(v=vs.85).aspx AppHelper.SetText(DiCapAxesTextBox, (device.Capabilities.AxeCount - slidersCount).ToString()); AppHelper.SetText(SlidersTextBox, slidersCount.ToString()); // Update PID and VID always so they wont be overwritten by load settings. short vid = BitConverter.ToInt16(di.ProductGuid.ToByteArray(), 0); short pid = BitConverter.ToInt16(di.ProductGuid.ToByteArray(), 2); AppHelper.SetText(DeviceVidTextBox, "0x{0:X4}", vid); AppHelper.SetText(DevicePidTextBox, "0x{0:X4}", pid); AppHelper.SetText(DeviceProductNameTextBox, di.ProductName); AppHelper.SetText(DeviceVendorNameTextBox, dInfo == null ? "" : dInfo.HidManufacturer); AppHelper.SetText(DeviceRevTextBox, "0x{0:X4}", dInfo == null ? 0 : dInfo.HidRevision); AppHelper.SetText(DeviceProductGuidTextBox, di.ProductGuid.ToString()); AppHelper.SetText(DeviceInstanceGuidTextBox, di.InstanceGuid.ToString()); AppHelper.SetText(DeviceTypeTextBox, di.Type.ToString()); }
public DirectInputDevice(Joystick joystick, string guid, string productName, bool hasForceFeedbackDevice, bool isHumanInterfaceDevice) { this.joystick = joystick; this.UniqueId = guid; this.DisplayName = productName; try { HardwareID = RawInput.RawDevices.GetHid(joystick.Properties.VendorId, joystick.Properties.ProductId); } catch (Exception e) { logger.Error(e, "Failed to get hid from WinAPI"); HardwareID = GetHid(joystick, isHumanInterfaceDevice); } var buttonObjectInstances = joystick.GetObjects(DeviceObjectTypeFlags.Button).Where(b => b.Usage > 0).OrderBy(b => b.ObjectId.InstanceNumber).Take(128).ToArray(); var buttons = buttonObjectInstances.Select((b, i) => MouseSource.FromButton(this, b, i)).ToArray(); var axes = GetAxes().OrderBy(a => a.Usage).Take(24).Select(a => MouseSource.FromAxis(this, a)); var sliders = joystick.GetObjects().Where(o => o.ObjectType == ObjectGuid.Slider).OrderBy(a => a.Usage).Select((s, i) => MouseSource.FromSlider(this, s, i)); IEnumerable <MouseSource> dpads = new MouseSource[0]; if (joystick.Capabilities.PovCount > 0) { dpads = Enumerable.Range(0, joystick.Capabilities.PovCount) .SelectMany(i => MouseSource.FromDPad(this, i)); } sources = buttons.Concat(axes).Concat(sliders).Concat(dpads).ToArray(); EffectInfo force = null; if (hasForceFeedbackDevice) { try { joystick.SetCooperativeLevel(WindowHandleStore.Handle, CooperativeLevel.Background | CooperativeLevel.Exclusive); } catch (Exception) { logger.Warn($"Failed to set cooperative level to exclusive for {ToString()}"); } var constantForce = joystick.GetEffects().FirstOrDefault(x => x.Guid == EffectGuid.ConstantForce); if (constantForce == null) { force = joystick.GetEffects().FirstOrDefault(); } else { force = constantForce; } var actuatorAxes = joystick.GetObjects().Where(doi => doi.ObjectId.Flags.HasFlag(DeviceObjectTypeFlags.ForceFeedbackActuator)).ToArray(); targets = actuatorAxes.Select(i => new ForceFeedbackTarget(this, i.Name, i.Offset)).ToArray(); forceFeedbacks = targets.ToDictionary(t => t, t => new DirectDeviceForceFeedback(joystick, UniqueId, force, actuatorAxes.First(a => a.Offset == t.Offset))); } else { targets = new ForceFeedbackTarget[0]; forceFeedbacks = new Dictionary <ForceFeedbackTarget, DirectDeviceForceFeedback>(); } joystick.Acquire(); inputChangedEventArgs = new DeviceInputChangedEventArgs(this); readThreadContext = ThreadCreator.CreateLoop($"{DisplayName} input reader", ReadLoop, 1).Start(); forceFeedbackThreadContext = ThreadCreator.CreateLoop($"{DisplayName} force feedback", ForceFeedbackLoop, 10).Start(); }
private static void TestPS4Controller(ICrazyradioDriver crazyradioDriver) { if (crazyradioDriver != null) { var crazyRadioMessenger = new CrazyflieMessenger(crazyradioDriver); var stopMotorsCommanderPacket = new CommanderPacket(roll: 0, pitch: 0, yaw: 0, thrust: 0); try { // Init float roll = 0; float pitch = 0; float yaw = 0; ushort thrust = 0; // Max/min values float rollRange = 50; float pitchRange = 50; float yawRange = 100; ushort thrustRange = 50000; // Stick ranges int stickRange = 1000; // Get first attached game controller found var directInput = new DirectInput(); var attahcedGameControllerDevices = directInput.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly); if (!attahcedGameControllerDevices.Any()) { throw new ApplicationException("No available game controllers found."); } var attachedDeviceInstance = attahcedGameControllerDevices.First(); var joystick = new Joystick(directInput, attachedDeviceInstance.InstanceGuid); foreach (DeviceObjectInstance doi in joystick.GetObjects(ObjectDeviceType.Axis)) { joystick.GetObjectPropertiesById((int)doi.ObjectType).SetRange(-1 * stickRange, stickRange); } joystick.Properties.AxisMode = DeviceAxisMode.Absolute; joystick.Acquire(); var joystickState = new JoystickState(); var loop = true; while (loop) { if (Console.KeyAvailable) { switch (Console.ReadKey().Key) { // end case ConsoleKey.Escape: loop = false; break; // pause case ConsoleKey.Spacebar: Log.InfoFormat("Paused...Hit SPACE to resume, ESC to quit."); thrust = 0; pitch = 0; yaw = 0; roll = 0; crazyRadioMessenger.SendMessage(stopMotorsCommanderPacket); var pauseLoop = true; while (pauseLoop) { if (Console.KeyAvailable) { switch (Console.ReadKey().Key) { // resume case ConsoleKey.Spacebar: pauseLoop = false; break; // end case ConsoleKey.Escape: pauseLoop = loop = false; break; } } } break; default: Log.InfoFormat("Invalid key for action."); break; } } // Poll the device and get state joystick.Poll(); joystick.GetCurrentState(ref joystickState); // Get buttons pressed info var stringWriter = new StringWriter(); var buttons = joystickState.GetButtons(); var anyButtonsPressed = buttons.Any(b => b == true); if (anyButtonsPressed) { for (int buttonNumber = 0; buttonNumber < buttons.Length; buttonNumber++) { if (buttons[buttonNumber] == true) { stringWriter.Write(string.Format("{0}", buttonNumber)); } } } var buttonsPressedString = stringWriter.ToString().Trim(); // Joystick info var leftStickX = joystickState.X; var leftStickY = joystickState.Y; var rightStickX = joystickState.RotationX; var rightStickY = joystickState.RotationY; roll = rollRange * rightStickX / stickRange; pitch = pitchRange * rightStickY / stickRange; yaw = yawRange * leftStickX / stickRange; thrust = (ushort)(leftStickY > 0 ? 0 : thrustRange * -1 * leftStickY / stickRange); var infoString = String.Format("LX:{0,7}, LY:{1,7}, RX:{2,7}, RY:{3,7}, Buttons:{4,7}.\tRoll:{5, 7}, Pitch:{6, 7}, Yaw:{7, 7}, Thrust:{8, 7}.", leftStickX, leftStickY, rightStickX, rightStickY, buttonsPressedString, roll, pitch, yaw, thrust); Console.WriteLine(infoString); var commanderPacket = new CommanderPacket(roll, pitch, yaw, thrust); crazyRadioMessenger.SendMessage(commanderPacket); } } catch (Exception) { try { crazyRadioMessenger.SendMessage(CommanderPacket.ZeroAll); } catch (Exception) { } throw; } crazyRadioMessenger.SendMessage(CommanderPacket.ZeroAll); } }
private static void Fly(CrazyflieCopter crazyflie) { ResetPositionEstimator(crazyflie); crazyflie.ParamConfigurator.SetValue("flightmode.posSet", (byte)0); try { for (int i = 0; i < 10; i++) { crazyflie.Commander.SendSetPoint(0, 0, 0, 0); } Thread.Sleep(200); crazyflie.Commander.SendSetPoint(0, 0, 0, 15000); // Init float roll = 0; float pitch = 0; float yaw = 0; ushort thrust = 0; // Max/min values float rollRange = 50; float pitchRange = 50; float yawRange = 100; ushort thrustRange = 50000; // Stick ranges int stickRange = 1000; // Get first attached game controller found var directInput = new DirectInput(); var attahcedGameControllerDevices = directInput.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly); if (!attahcedGameControllerDevices.Any()) { throw new ApplicationException("No available game controllers found."); } var attachedDeviceInstance = attahcedGameControllerDevices.First(); var joystick = new Joystick(directInput, attachedDeviceInstance.InstanceGuid); foreach (DeviceObjectInstance doi in joystick.GetObjects(ObjectDeviceType.Axis)) { joystick.GetObjectPropertiesById((int)doi.ObjectType).SetRange(-1 * stickRange, stickRange); } joystick.Properties.AxisMode = DeviceAxisMode.Absolute; joystick.Acquire(); var joystickState = new JoystickState(); var loop = true; while (loop) { if (Console.KeyAvailable) { switch (Console.ReadKey().Key) { // end case ConsoleKey.Escape: loop = false; break; // pause case ConsoleKey.Spacebar: loop = LandAndPause(crazyflie); continue; default: Log.InfoFormat("Invalid key for action."); break; } } // Poll the device and get state joystick.Poll(); joystick.GetCurrentState(ref joystickState); // Get buttons pressed info var stringWriter = new StringWriter(); var buttons = joystickState.GetButtons(); var anyButtonsPressed = buttons.Any(b => b == true); if (anyButtonsPressed) { for (int buttonNumber = 0; buttonNumber < buttons.Length; buttonNumber++) { if (buttons[buttonNumber] == true) { stringWriter.Write(string.Format("{0}", buttonNumber)); } } } var buttonsPressedString = stringWriter.ToString().Trim(); // Joystick info var leftStickX = joystickState.X; var leftStickY = joystickState.Y; var rightStickX = joystickState.RotationX; var rightStickY = joystickState.RotationY; roll = rollRange * rightStickX / stickRange; pitch = pitchRange * rightStickY / stickRange; yaw = yawRange * leftStickX / stickRange; thrust = (ushort)(leftStickY > 0 ? 0 : thrustRange * -1 * leftStickY / stickRange); var infoString = String.Format("LX:{0,7}, LY:{1,7}, RX:{2,7}, RY:{3,7}, Buttons:{4,7}.\tRoll:{5, 7}, Pitch:{6, 7}, Yaw:{7, 7}, Thrust:{8, 7}.", leftStickX, leftStickY, rightStickX, rightStickY, buttonsPressedString, roll, pitch, yaw, thrust); Console.WriteLine(infoString); Thread.Sleep(20); crazyflie.Commander.SendSetPoint(roll, pitch, yaw, thrust); } } catch (Exception) { try { crazyflie.Commander.SendStopSetPoint(); } catch (Exception) { } throw; } crazyflie.Commander.SendStopSetPoint(); }
private Boolean getFirstPressedButton(System.Windows.Forms.Form parent, ControllerData controllerData, ButtonAssignment buttonAssignment) { Boolean gotAssignment = false; if (controllerData.guid == UDP_NETWORK_CONTROLLER_GUID) { int assignedButton; if (CrewChief.gameDefinition.gameEnum == GameEnum.PCARS_NETWORK) { PCarsUDPreader gameDataReader = (PCarsUDPreader)GameStateReaderFactory.getInstance().getGameStateReader(GameDefinition.pCarsNetwork); assignedButton = gameDataReader.getButtonIndexForAssignment(); } else { PCars2UDPreader gameDataReader = (PCars2UDPreader)GameStateReaderFactory.getInstance().getGameStateReader(GameDefinition.pCars2Network); assignedButton = gameDataReader.getButtonIndexForAssignment(); } if (assignedButton != -1) { removeAssignmentsForControllerAndButton(controllerData.guid, assignedButton); buttonAssignment.controller = controllerData; buttonAssignment.buttonIndex = assignedButton; listenForAssignment = false; gotAssignment = true; } } else { listenForAssignment = true; // Instantiate the joystick try { var joystick = new Joystick(directInput, controllerData.guid); // Acquire the joystick joystick.SetCooperativeLevel(parent, (CooperativeLevel.NonExclusive | CooperativeLevel.Background)); joystick.Properties.BufferSize = 128; joystick.Acquire(); while (listenForAssignment) { Boolean[] buttons = joystick.GetCurrentState().Buttons; for (int i = 0; i < buttons.Count(); i++) { if (buttons[i]) { Console.WriteLine("Got button at index " + i); removeAssignmentsForControllerAndButton(controllerData.guid, i); buttonAssignment.controller = controllerData; buttonAssignment.joystick = joystick; buttonAssignment.buttonIndex = i; listenForAssignment = false; gotAssignment = true; } } if (!gotAssignment) { Thread.Sleep(20); } } if (!gotAssignment) { joystick.Unacquire(); } } catch (Exception e) { Console.WriteLine("Unable to acquire device " + controllerData.deviceName + " error: " + e.Message); listenForAssignment = false; gotAssignment = false; } } return(gotAssignment); }
public bool ForceFeedback2(string productGuid, string productName, bool AutoCenter, int ForceFeedbackGain) { // Initialize DirectInput var directInput = new DirectInput(); var product = new Guid(productGuid); // Find a Joystick Guid var joystickGuid = Guid.Empty; var joystickName = String.Empty; var directInputDevices = new List <DeviceInstance>(); directInputDevices.AddRange(directInput.GetDevices()); //directInputDevices.AddRange(directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)); //directInputDevices.AddRange(directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)); //directInputDevices.AddRange(directInput.GetDevices(DeviceType.Driving, DeviceEnumerationFlags.AllDevices)); foreach (var deviceInstance in directInputDevices) { Console.WriteLine($"DeviceName: {deviceInstance.ProductName}: ProductGuid {deviceInstance.ProductGuid}"); if (deviceInstance.ProductGuid == product || deviceInstance.ProductName == productName) { joystickGuid = deviceInstance.InstanceGuid; joystickName = deviceInstance.ProductName; break; } } // If Joystick not found, throws an error if (joystickGuid == Guid.Empty) { Console.WriteLine("No matching Joystick/Gamepad/Wheel found. {deviceInstance.ProductName} {productGuid}"); return(false); } // Instantiate the joystick joystick = new Joystick(directInput, joystickGuid); Console.WriteLine("Found Joystick/Gamepad {0}", joystickName); // Query all suported ForceFeedback effects var allEffects = joystick.GetEffects(); foreach (var effectInfo in allEffects) { knownEffects.Add(effectInfo.Name, effectInfo); Console.WriteLine("Effect available {0}", effectInfo.Name); } // Load all of the effect files var forcesFolder = new DirectoryInfo(@".\Forces"); foreach (var file in forcesFolder.GetFiles("*.ffe")) { var effectsFromFile = joystick.GetEffectsInFile(file.FullName, EffectFileFlags.ModidyIfNeeded); fileEffects.Add(file.Name, new List <EffectFile>(effectsFromFile)); Console.WriteLine($"File Effect available {file.Name}"); } // Set BufferSize in order to use buffered data. joystick.Properties.BufferSize = 128; // DirectX requires a window handle to set the CooperativeLevel var handle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; try { joystick.SetCooperativeLevel(handle, CooperativeLevel.Exclusive | CooperativeLevel.Background); } catch (SharpDX.SharpDXException ex) when((uint)ex.HResult == WINDOW_HANDLE_ERROR) { Console.WriteLine(); Console.WriteLine(); Console.WriteLine($"***********************************************************************************"); Console.WriteLine(); Console.WriteLine($" Unable to access window handle. Do not run EDForceFeedback.exe in a console window."); Console.WriteLine(); Console.WriteLine($"***********************************************************************************"); Console.WriteLine(); Console.WriteLine(); return(false); } try { // Autocenter on joystick.Properties.AutoCenter = AutoCenter; } catch (Exception _) { // Some devices do not support this setting. } // Acquire the joystick joystick.Acquire(); //var test = joystick.Properties.ForceFeedbackGain; joystick.Properties.ForceFeedbackGain = ForceFeedbackGain; return(true); }
private void LoadJoysticks() { DirectInput di = new DirectInput(); List<DeviceInstance> devices = new List<DeviceInstance>(); devices.AddRange(di.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly)); foreach (DeviceInstance i in devices) { if (i.Type == DeviceType.Joystick) { Joystick j = new Joystick(di, i.InstanceGuid); j.Acquire(); sticks.Add(j); stickstate.Add(j.GetCurrentState()); } } // set up a timer to poll joystick state at 10Hz timer.Tick += new EventHandler(timer_Tick); timer.Interval = new TimeSpan(0, 0, 0, 0, 100); timer.Start(); }
static void Main() { // Initialize DirectInput var directInput = new DirectInput(); // Find a Joystick Guid var joystickGuid = Guid.Empty; foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)) { joystickGuid = deviceInstance.InstanceGuid; } // If Gamepad not found, look for a Joystick if (joystickGuid == Guid.Empty) { foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) { joystickGuid = deviceInstance.InstanceGuid; } } // If Joystick not found, throws an error if (joystickGuid == Guid.Empty) { Console.WriteLine("No joystick/Gamepad found."); Console.ReadKey(); Environment.Exit(1); } // Instantiate the joystick var joystick = new Joystick(directInput, joystickGuid); Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid); // Query all suported ForceFeedback effects var allEffects = joystick.GetEffects(); foreach (var effectInfo in allEffects) { Console.WriteLine("Effect available {0}", effectInfo.Name); } // Set BufferSize in order to use buffered data. joystick.Properties.BufferSize = 128; // Acquire the joystick joystick.Acquire(); // Poll events from joystick while (true) { joystick.Poll(); var datas = joystick.GetBufferedData(); foreach (var state in datas) { Console.WriteLine(state); } } }
List<string> ShowDirectInputState(Joystick device) { JoystickState state = null; if (device != null) { try { device.Acquire(); state = device.GetCurrentState(); } catch (Exception ex) { var error = ex; } } if (state == null || state.Equals(oldState)) return actions; // Fill axis. Axis[0] = state.X; Axis[1] = state.Y; Axis[2] = state.Z; Axis[3] = state.RotationX; Axis[4] = state.RotationY; Axis[5] = state.RotationZ; oldState = state; actions.Clear(); // X-axis. DiAxisTable.Rows[0][1] = state.X; DiAxisTable.Rows[0][2] = state.RotationX; DiAxisTable.Rows[0][3] = state.AccelerationX; DiAxisTable.Rows[0][4] = state.AngularAccelerationX; DiAxisTable.Rows[0][5] = state.ForceX; DiAxisTable.Rows[0][6] = state.TorqueX; DiAxisTable.Rows[0][7] = state.VelocityX; DiAxisTable.Rows[0][8] = state.AngularVelocityX; // Y-axis. DiAxisTable.Rows[1][1] = state.Y; DiAxisTable.Rows[1][2] = state.RotationY; DiAxisTable.Rows[1][3] = state.AccelerationY; DiAxisTable.Rows[1][4] = state.AngularAccelerationY; DiAxisTable.Rows[1][5] = state.ForceY; DiAxisTable.Rows[1][6] = state.TorqueY; DiAxisTable.Rows[1][7] = state.VelocityY; DiAxisTable.Rows[1][8] = state.AngularVelocityY; // Z-axis. DiAxisTable.Rows[2][1] = state.Z; DiAxisTable.Rows[2][2] = state.RotationZ; DiAxisTable.Rows[2][3] = state.AccelerationZ; DiAxisTable.Rows[2][4] = state.AngularAccelerationZ; DiAxisTable.Rows[2][5] = state.ForceZ; DiAxisTable.Rows[2][6] = state.TorqueZ; DiAxisTable.Rows[2][7] = state.VelocityZ; DiAxisTable.Rows[2][8] = state.AngularVelocityZ; var rows = DiAxisTable.Rows; var cols = DiAxisTable.Columns; int v; int axisNum; for (int r = 0; r < rows.Count; r++) { for (int c = 1; c < cols.Count; c++) { if (System.DBNull.Value == rows[r][c]) continue; v = (int)rows[r][c]; axisNum = (c - 1) * rows.Count + r + 1; addAction(actions, v, "Axis", axisNum); } } bool[] buttons = state.Buttons; DiButtonsTextBox.Text = ""; if (buttons != null) { for (int i = 0; i < buttons.Length; i++) { if (buttons[i]) { actions.Add(string.Format("Button {0}", i + 1)); if (DiButtonsTextBox.Text.Length > 0) DiButtonsTextBox.Text += " "; DiButtonsTextBox.Text += (i + 1).ToString("00"); } } } // Sliders var sNum = 1; ProcessSlider(actions, state.Sliders, DiUvSliderTextBox, ref sNum); ProcessSlider(actions, state.AccelerationSliders, DiASliderTextBox, ref sNum); ProcessSlider(actions, state.ForceSliders, DiFSliderTextBox, ref sNum); ProcessSlider(actions, state.VelocitySliders, DiVSliderTextBox, ref sNum); // Point of view buttons int[] dPad = state.PointOfViewControllers; DiDPadTextBox.Text = ""; if (dPad != null) { for (int i = 0; i < dPad.Length; i++) { v = dPad[i]; if (DiDPadTextBox.Text.Length > 0) DiDPadTextBox.Text += " "; if (v != -1) { DiDPadTextBox.Text += "[" + i + "," + v.ToString() + "]"; if ((DPadEnum)v == DPadEnum.Up) actions.Add(string.Format("DPad {0} {1}", i + 1, DPadEnum.Up.ToString())); if ((DPadEnum)v == DPadEnum.Right) actions.Add(string.Format("DPad {0} {1}", i + 1, DPadEnum.Right.ToString())); if ((DPadEnum)v == DPadEnum.Down) actions.Add(string.Format("DPad {0} {1}", i + 1, DPadEnum.Down.ToString())); if ((DPadEnum)v == DPadEnum.Left) actions.Add(string.Format("DPad {0} {1}", i + 1, DPadEnum.Left.ToString())); } } } return actions; }
private void Awake() { joystick = FindObjectOfType <PlayerData>().controllers[playerNumber]; if (joystick == null) { Destroy(gameObject); } else { if (joystick.Information.Type == SharpDX.DirectInput.DeviceType.Keyboard) { keyboard = true; } if (playerNumber <= 2) { if (playerNumber == 1) { button1 = 33; button2 = 34; dreapta = 31; stanga = 29; jos = 30; sus = 16; } else { button1 = 53; button2 = 91; dreapta = 107; stanga = 106; jos = 109; sus = 104; } } else { if (joystick.Information.ProductName == "USB Network Joystick") { button1 = 2; button2 = 3; } else { button1 = 0; button2 = 2; } } joystick.Acquire(); } bool ok = false; foreach (int player in FindObjectOfType <PlayerData>().players) { if (playerNumber == player) { ok = true; spriteColor1.color = FindObjectOfType <PlayerData>().color1[playerNumber]; spriteColor2.color = FindObjectOfType <PlayerData>().color2[playerNumber]; } } if (ok == false) { Destroy(gameObject); } else { teamColor.text = FindObjectOfType <PlayerData>().playerNames[playerNumber]; if (FindObjectOfType <PlayerData>().teams == true) { team = FindObjectOfType <PlayerData>().playerTeams[playerNumber]; if (team == 0) { teamColor.color = new Color32(0, 175, 255, 255); } else { teamColor.color = new Color32(255, 0, 0, 255); } } else { teamColor.color = new Color32(255, 255, 255, 255); } FindObjectOfType <SpawnPlayers>().players.Add(gameObject); } }
public static Joystick StartGamePad() { // Initialize DirectInput var directInput = new DirectInput(); // Find a Joystick Guid var joystickGuid = Guid.Empty; foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)) { joystickGuid = deviceInstance.InstanceGuid; } // If Gamepad not found, look for a Joystick if (joystickGuid == Guid.Empty) { foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) { joystickGuid = deviceInstance.InstanceGuid; } } // If Joystick not found, throws an error if (joystickGuid == Guid.Empty) { MainWindow.GPID = "No Gamepad found."; Environment.Exit(1); } // Instantiate the joystick var joystick = new Joystick(directInput, joystickGuid); MainWindow.GPID = "Gamepad GUID: " + joystickGuid; // Query all suported ForceFeedback effects var allEffects = joystick.GetEffects(); foreach (var effectInfo in allEffects) { Console.WriteLine("Effect available {0}", effectInfo.Name); } // Set BufferSize in order to use buffered data. joystick.Properties.BufferSize = 128; // Acquire the joystick joystick.Acquire(); // Poll events from joystick // while (true) // { // joystick.Poll(); // var datas = joystick.GetBufferedData(); // foreach (var state in datas) // Console.WriteLine(state); //} return(joystick); }
public ControllerDevice[] detectControllers() { for (int i = 0; i < 4; i++) //Remove disconnected controllers { if (devices[i] != null && !directInput.IsDeviceAttached(devices[i].joystick.Information.InstanceGuid)) { Console.WriteLine(devices[i].joystick.Properties.InstanceName + " Removed"); devices[i] = null; workers[i].Abort(); workers[i] = null; Unplug(i + 1); } } foreach (var deviceInstance in directInput.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly)) { Joystick joystick = new Joystick(directInput, deviceInstance.InstanceGuid); if (joystick.Information.ProductGuid.ToString() == "028e045e-0000-0000-0000-504944564944") //If its an emulated controller skip it { continue; } if (joystick.Capabilities.ButtonCount < 1 && joystick.Capabilities.AxesCount < 1) //Skip if it doesn't have any button and axes { continue; } int spot = -1; for (int i = 0; i < 4; i++) { if (devices[i] == null) { if (spot == -1) { spot = i; Console.WriteLine("Open Spot " + i.ToString()); } } else if (devices[i] != null && devices[i].joystick.Information.InstanceGuid == deviceInstance.InstanceGuid) //If the device is already initialized skip it { Console.WriteLine("Controller Already Acquired " + i.ToString() + " " + deviceInstance.InstanceName); spot = -1; break; } } if (spot == -1) { continue; } if (isExclusive) { joystick.SetCooperativeLevel(handle, CooperativeLevel.Exclusive | CooperativeLevel.Background); } else { joystick.SetCooperativeLevel(handle, CooperativeLevel.Nonexclusive | CooperativeLevel.Background); } joystick.Properties.BufferSize = 128; joystick.Acquire(); devices[spot] = new ControllerDevice(joystick, spot + 1); if (IsActive) { processingData[spot] = new ContData(); Console.WriteLine("Plug " + spot); Plugin(spot + 1); int t = spot; workers[spot] = new Thread(() => { ProcessData(t); }); workers[spot].Start(); } } return(devices); }
private void JoyStickCall(object sender, DoWorkEventArgs e) { // Initialize DirectInput var directInput = new DirectInput(); // Find a Joystick Guid var joystickGuid = Guid.Empty; foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)) { joystickGuid = deviceInstance.InstanceGuid; } // If Gamepad not found, look for a Joystick if (joystickGuid == Guid.Empty) { foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) { joystickGuid = deviceInstance.InstanceGuid; } } // If Joystick not found, throws an error if (joystickGuid == Guid.Empty) { Console.WriteLine("No joystick/Gamepad found."); Console.ReadKey(); Environment.Exit(1); } // Instantiate the joystick var joystick = new Joystick(directInput, joystickGuid); Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid); // Query all suported ForceFeedback effects var allEffects = joystick.GetEffects(); foreach (var effectInfo in allEffects) { Console.WriteLine("Effect available {0}", effectInfo.Name); } // Set BufferSize in order to use buffered data. joystick.Properties.BufferSize = 128; // Acquire the joystick joystick.Acquire(); // Poll events from joystick while (true) { joystick.Poll(); var datas = joystick.GetCurrentState(); Application.DoEvents(); Thread.Sleep(1); //joystickData[0] = mapInt(Int32.Parse(datas.PointOfViewControllers.GetValue(0).ToString()), 0, 65534, 0, 255); //joystickData[1] = mapInt(Int32.Parse(datas.Y.ToString()), 0, 65534, 0, 255, 1); // min is bottom max is top L-STICK UP-DOWN "0-255" joystickData[2] = mapInt(Int32.Parse(datas.X.ToString()), 0, 65534, -150, 150); //L-STICK LEFT-RIGHT "-500-500" //roll %30 of 1000 us, total 300 uS joystickData[3] = mapInt(Int32.Parse(datas.Y.ToString()), 0, 65534, -350, 350, 1); //L-STICK UP-DOWN //throttle %70 of 1000 uS, total 700 uS if (controllerType == 1) { //FOR DUALSHOCK 3 joystickData[4] = mapInt(Int32.Parse(datas.RotationX.ToString()), 0, 65534, -400, 400); //R-STICK LEFT-RIGHT "-1000 -1000" %40 of 1000 us, OTHER %20 IS FOR YAW AXIS joystickData[5] = mapInt(Int32.Parse(datas.RotationY.ToString()), 0, 65534, -400, 400, 1); //R-STICK UP-DOWN "--1000-1000" %40 of 1000 us } if (controllerType == 0) { //FOR DUALSHOCK 2 joystickData[4] = mapInt(Int32.Parse(datas.Z.ToString()), 0, 65534, -400, 400); joystickData[5] = mapInt(Int32.Parse(datas.RotationZ.ToString()), 0, 65534, -400, 400, 1); } joystickData[6] = Convert.ToInt32(datas.Buttons.GetValue(2)); //SQUARE joystickData[7] = Convert.ToInt32(datas.Buttons.GetValue(1)); //O joystickData[8] = Convert.ToInt32(datas.Buttons.GetValue(0)); //X joystickData[9] = Convert.ToInt32(datas.Buttons.GetValue(3)); //Triangle joystickData[10] = Convert.ToInt32(datas.Buttons.GetValue(7)); //START joystickData[11] = Convert.ToInt32(datas.Buttons.GetValue(5)); //R1 joystickData[12] = Convert.ToInt32(datas.Buttons.GetValue(6)); //SELECT joystickData[13] = Convert.ToInt32(datas.Buttons.GetValue(4)); //L1 joystickData[14] = Convert.ToInt32(datas.Buttons.GetValue(9)); //R3 joystickData[15] = Convert.ToInt32(datas.Buttons.GetValue(8)); //L3 joystickData[16] = mapInt(Int32.Parse(datas.Z.ToString()), 0, 65534, -200, 200); //R2 L2 --Yaw value %20 of 1000 us //DEBUGGING //var datass = joystick.GetBufferedData(); //foreach (var dt in datass) // Console.WriteLine(dt); //DEBUGGING iteration = iteration + 1; System.Threading.Thread.Sleep(5); Application.DoEvents(); } }
static void Main(string[] args) { string name; string message; StringComparer stringComparer = StringComparer.OrdinalIgnoreCase; Thread readThread = new Thread(Read); // Create a new SerialPort object with default settings. _serialPort = new SerialPort(); // Allow the user to set the appropriate properties. _serialPort.PortName = "COM8"; //SetPortName(_serialPort.PortName); _serialPort.BaudRate = 9600; //SetPortBaudRate(_serialPort.BaudRate); _serialPort.Parity = SetPortParity(_serialPort.Parity); _serialPort.DataBits = 8; //SetPortDataBits(_serialPort.DataBits); _serialPort.StopBits = (StopBits)1; //SetPortStopBits(_serialPort.StopBits); _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake); // Set the read/write timeouts _serialPort.ReadTimeout = 500; _serialPort.WriteTimeout = 500; _serialPort.Open(); _continue = true; readThread.Start(); s /*Console.Write("Name: "); * name = Console.ReadLine(); * * Console.WriteLine("Type QUIT to exit"); */ Console.WriteLine("Please Wait"); // Initialize DirectInput var directInput = new DirectInput(); // Find a Joystick Guid var joystickGuid = Guid.Empty; foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)) { joystickGuid = deviceInstance.InstanceGuid; } // If Gamepad not found, look for a Joystick if (joystickGuid == Guid.Empty) { foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) { joystickGuid = deviceInstance.InstanceGuid; } } // If Joystick not found, throws an error if (joystickGuid == Guid.Empty) { Console.WriteLine("No joystick/Gamepad found."); Console.ReadKey(); Environment.Exit(1); } // Instantiate the joystick var joystick = new Joystick(directInput, joystickGuid); Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid); // Query all suported ForceFeedback effects var allEffects = joystick.GetEffects(); foreach (var effectInfo in allEffects) { Console.WriteLine("Effect available {0}", effectInfo.Name); } // Set BufferSize in order to use buffered data. joystick.Properties.BufferSize = 128; // Acquire the joystick joystick.Acquire(); // Poll events from joystick while (_continue) { joystick.Poll(); var datas = joystick.GetBufferedData(); foreach (var state in datas) { String temp = ""; String offset = state.Offset.ToString(); int value = state.Value; if (offset == "Y") { temp = "[L" + value + "]\r\n"; } else if (offset == "RotationY") { temp = "[R" + value + "]\r\n"; } else if (offset == "Buttons0" && value == 128) { temp = "X\r\n"; } else if (offset == "Buttons0" && value == 0) { temp = "x\r\n"; } else if (offset == "Buttons1" && value == 128) { temp = "C\r\n"; } else if (offset == "Buttons1" && value == 0) { temp = "c\r\n"; } else if (offset == "Buttons2" && value == 128) { temp = "S\r\n"; } else if (offset == "Buttons2" && value == 0) { temp = "s\r\n"; } else if (offset == "Buttons3" && value == 128) { temp = "T\r\n"; } else if (offset == "Buttons3" && value == 0) { temp = "t\r\n"; } Console.Write(temp); _serialPort.WriteLine(temp); } } readThread.Join(); _serialPort.Close(); }
public void UpdateFrom(Joystick device, out JoystickState state) { if (!AppHelper.IsSameDevice(device, deviceInstanceGuid)) { ShowDeviceInfo(device); deviceInstanceGuid = Guid.Empty; if (device != null) { deviceInstanceGuid = device.Information.InstanceGuid; isWheel = device.Information.Type == SharpDX.DirectInput.DeviceType.Driving; } } state = null; if (device != null) { try { device.Acquire(); state = device.GetCurrentState(); } catch (Exception ex) { var error = ex; } } ShowDirectInputState(state); }
void ShowDeviceInfo(Joystick device) { if (device == null) { // clean everything here. SetValue(DeviceProductNameTextBox, ""); SetValue(DeviceProductGuidTextBox, ""); SetValue(DeviceInstanceGuidTextBox, ""); DiCapFfStateTextBox.Text = string.Empty; DiCapAxesTextBox.Text = string.Empty; DiCapButtonsTextBox.Text = string.Empty; DiCapDPadsTextBox.Text = string.Empty; DiEffectsTable.Rows.Clear(); return; } lock (MainForm.XInputLock) { var isLoaded = XInput.IsLoaded; if (isLoaded) { XInput.FreeLibrary(); } device.Unacquire(); device.SetCooperativeLevel(MainForm.Current, CooperativeLevel.Foreground | CooperativeLevel.Exclusive); effects = new List <EffectInfo>(); try { device.Acquire(); var forceFeedback = device.Capabilities.Flags.HasFlag(DeviceFlags.ForceFeedback); forceFeedbackState = forceFeedback ? "YES" : "NO"; effects = device.GetEffects(EffectType.All); } catch (Exception) { forceFeedbackState = "ERROR"; } DiEffectsTable.Rows.Clear(); foreach (var eff in effects) { DiEffectsTable.Rows.Add(new object[] { eff.Name, ((EffectParameterFlags)eff.StaticParameters).ToString(), ((EffectParameterFlags)eff.DynamicParameters).ToString() }); } device.Unacquire(); device.SetCooperativeLevel(MainForm.Current, CooperativeLevel.Background | CooperativeLevel.NonExclusive); if (isLoaded) { Exception error; XInput.ReLoadLibrary(XInput.LibraryName, out error); } } DiCapFfStateTextBox.Text = forceFeedbackState; DiCapButtonsTextBox.Text = device.Capabilities.ButtonCount.ToString(); DiCapDPadsTextBox.Text = device.Capabilities.PovCount.ToString(); var objects = device.GetObjects(DeviceObjectTypeFlags.All).OrderBy(x => x.Offset).ToArray(); DiObjectsTable.Rows.Clear(); var og = typeof(SharpDX.DirectInput.ObjectGuid); var guidFileds = og.GetFields().Where(x => x.FieldType == typeof(Guid)); List <Guid> guids = guidFileds.Select(x => (Guid)x.GetValue(og)).ToList(); List <string> names = guidFileds.Select(x => x.Name).ToList(); foreach (var o in objects) { DiObjectsTable.Rows.Add(new object[] { o.Offset, o.ObjectId.InstanceNumber, o.Usage, o.Name, o.Aspect, guids.Contains(o.ObjectType) ? names[guids.IndexOf(o.ObjectType)] : o.ObjectType.ToString(), o.ObjectId.Flags, }); } var actuators = objects.Where(x => x.ObjectId.Flags.HasFlag(DeviceObjectTypeFlags.ForceFeedbackActuator)); ActuatorsTextBox.Text = actuators.Count().ToString(); var di = device.Information; var slidersCount = objects.Where(x => x.ObjectType.Equals(SharpDX.DirectInput.ObjectGuid.Slider)).Count(); DiCapAxesTextBox.Text = (device.Capabilities.AxeCount - slidersCount).ToString(); SlidersTextBox.Text = slidersCount.ToString(); // Update PID and VID always so they wont be overwritten by load settings. short vid = BitConverter.ToInt16(di.ProductGuid.ToByteArray(), 0); short pid = BitConverter.ToInt16(di.ProductGuid.ToByteArray(), 2); SetValue(DeviceVidTextBox, "0x{0}", vid.ToString("X4")); SetValue(DevicePidTextBox, "0x{0}", pid.ToString("X4")); SetValue(DeviceProductNameTextBox, di.ProductName); SetValue(DeviceProductGuidTextBox, di.ProductGuid.ToString()); SetValue(DeviceInstanceGuidTextBox, di.InstanceGuid.ToString()); SetValue(DeviceTypeTextBox, di.Type.ToString()); }
public void ForceFeedback2(string productGuid = "001b045e-0000-0000-0000-504944564944") { // Initialize DirectInput var directInput = new DirectInput(); var product = new Guid(productGuid); // Find a Joystick Guid var joystickGuid = Guid.Empty; foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) { if (deviceInstance.ProductGuid == product) { joystickGuid = deviceInstance.InstanceGuid; break; } } // If Joystick not found, throws an error if (joystickGuid == Guid.Empty) { Console.WriteLine("No joystick/Gamepad found."); Console.ReadKey(); Environment.Exit(1); } // Instantiate the joystick joystick = new Joystick(directInput, joystickGuid); Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid); // Query all suported ForceFeedback effects var allEffects = joystick.GetEffects(); foreach (var effectInfo in allEffects) { knownEffects.Add(effectInfo.Name, effectInfo); Console.WriteLine("Effect available {0}", effectInfo.Name); } // Load all of the effect files var forcesFolder = new DirectoryInfo(@".\Forces"); foreach (var file in forcesFolder.GetFiles("*.ffe")) { var effectsFromFile = joystick.GetEffectsInFile(file.FullName, EffectFileFlags.ModidyIfNeeded); fileEffects.Add(file.Name, new List <EffectFile>(effectsFromFile)); Console.WriteLine($"File Effect available {file.Name}"); } // Set BufferSize in order to use buffered data. joystick.Properties.BufferSize = 128; // DirectX requires a window handle to set the CooperativeLevel var handle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; joystick.SetCooperativeLevel(handle, CooperativeLevel.Exclusive | CooperativeLevel.Background); // Autocenter on joystick.Properties.AutoCenter = true; // Acquire the joystick joystick.Acquire(); //var test = joystick.Properties.ForceFeedbackGain; joystick.Properties.ForceFeedbackGain = 10000; }
/// <summary> /// Initializes a joystick device using the specified global unique identifier. /// </summary> /// <param name="handle">A pointer to the application's master form.</param> /// <param name="g">The GUID of the device to initialize.</param> public static ForceFeedbackStatus DInputInit(IntPtr handle, Guid g) { if (JSDevice != null) { JSDevice.Unacquire(); JSDevice = null; } JSDevice = new Joystick(input, g); int xAxisOffset = 0, yAxisOffset = 0; int nextOffset = 0; // JSDevice.Properties.AutoCenter = true; foreach (DeviceObjectInstance d in JSDevice.GetObjects()) { if ((d.ObjectId.Flags & DeviceObjectTypeFlags.ForceFeedbackActuator) == DeviceObjectTypeFlags.ForceFeedbackActuator) { if (nextOffset == 0) { xAxisOffset = d.Offset; } else { yAxisOffset = d.Offset; } nextOffset++; } if (d.ObjectType == ObjectGuid.XAxis) { JSDevice.GetObjectPropertiesById( d.ObjectId).Range = new InputRange(-5, 5); JSDevice.GetObjectPropertiesById( d.ObjectId).DeadZone = 1000; } if (d.ObjectType == ObjectGuid.YAxis) { JSDevice.GetObjectPropertiesById(d.ObjectId).Range = new InputRange(-9, 9); JSDevice.GetObjectPropertiesById( d.ObjectId).DeadZone = 1000; } if (d.ObjectType == ObjectGuid.Slider) { JSDevice.GetObjectPropertiesById( d.ObjectId).Range = new InputRange(0, 11); JSSliderId = d.ObjectId; useSlider = true; } if (d.ObjectType == ObjectGuid.ZAxis) { JSDevice.GetObjectPropertiesById( d.ObjectId).Range = new InputRange(0, 11); jsZId = d.ObjectId; useZ = true; } if (d.ObjectType == ObjectGuid.RzAxis) { JSDevice.GetObjectPropertiesById( d.ObjectId).Range = new InputRange(-5, 5); } } //for if (useSlider && useZ) { useSlider = false; } JSDevice.SetCooperativeLevel(handle, CooperativeLevel.Background | CooperativeLevel.Exclusive); JSDevice.Acquire(); updateJSState(); TheJSButtons = JSState.Buttons; if (nextOffset > 0) { if (!dInputInitFD(JSDevice, xAxisOffset, yAxisOffset, nextOffset)) { forceFeedbackEnabled = false; return(ForceFeedbackStatus.couldNotInitialize); } else { forceFeedbackEnabled = true; return(ForceFeedbackStatus.initialized); } } return(ForceFeedbackStatus.noForceFeedback); }
public void OnTick() { try { if (_joystick.Disposed || _joystick.Acquire().IsFailure || _joystick.Poll().IsFailure || Result.Last.IsFailure) { return; } var state = _joystick.GetCurrentState(); for (var i = 0; i < Axis.Length; i++) { var a = Axis[i]; a.Value = GetAxisValue(a.Id, state); } var buttons = state.GetButtons(); for (var i = 0; i < Buttons.Length; i++) { var b = Buttons[i]; b.Value = b.Id < buttons.Length && buttons[b.Id]; } var povs = state.GetPointOfViewControllers(); for (var i = 0; i < Povs.Length; i++) { var b = Povs[i]; b.Value = b.Direction.IsInRange(b.Id < povs.Length ? povs[b.Id] : -1); } } catch (DirectInputException e) when(e.Message.Contains(@"DIERR_UNPLUGGED")) { Unplugged = true; } catch (DirectInputException e) { if (!Error) { Logging.Warning("Exception: " + e); Error = true; } } double GetAxisValue(int id, JoystickState state) { switch (id) { case 0: return(state.X / 65535d); case 1: return(state.Y / 65535d); case 2: return(state.Z / 65535d); case 3: return(state.RotationX / 65535d); case 4: return(state.RotationY / 65535d); case 5: return(state.RotationZ / 65535d); case 6: return(state.GetSliders().Length > 0 ? state.GetSliders()[0] / 65535d : 0d); case 7: return(state.GetSliders().Length > 1 ? state.GetSliders()[1] / 65535d : 0d); default: return(0); } } }
public override GamePadState GetState() { var gamePadState = new GamePadState(); // Get the current joystick state try { if (instance == null) { if (directInput.IsDeviceAttached(key.Guid)) { instance = new Joystick(directInput, key.Guid); } else { return(gamePadState); } } // Acquire the joystick instance.Acquire(); // Make sure that the latest state is up to date instance.Poll(); // Get the state instance.GetCurrentState(ref joystickState); } catch (SharpDX.SharpDXException) { // If there was an exception, dispose the native instance try { if (instance != null) { instance.Dispose(); instance = null; } // Return a GamePadState that specify that it is not connected return(gamePadState); } catch (Exception) { } } //Console.WriteLine(joystickState); gamePadState.IsConnected = true; gamePadState.Buttons = GamePadButton.None; if (joystickState.Buttons[0]) { gamePadState.Buttons |= GamePadButton.X; } if (joystickState.Buttons[1]) { gamePadState.Buttons |= GamePadButton.A; } if (joystickState.Buttons[2]) { gamePadState.Buttons |= GamePadButton.B; } if (joystickState.Buttons[3]) { gamePadState.Buttons |= GamePadButton.Y; } if (joystickState.Buttons[4]) { gamePadState.Buttons |= GamePadButton.LeftShoulder; } if (joystickState.Buttons[5]) { gamePadState.Buttons |= GamePadButton.RightShoulder; } if (joystickState.Buttons[6]) { gamePadState.LeftTrigger = 1.0f; } if (joystickState.Buttons[7]) { gamePadState.RightTrigger = 1.0f; } if (joystickState.Buttons[8]) { gamePadState.Buttons |= GamePadButton.Back; } if (joystickState.Buttons[9]) { gamePadState.Buttons |= GamePadButton.Start; } if (joystickState.Buttons[10]) { gamePadState.Buttons |= GamePadButton.LeftThumb; } if (joystickState.Buttons[11]) { gamePadState.Buttons |= GamePadButton.RightThumb; } int dPadRawValue = joystickState.PointOfViewControllers[0]; if (dPadRawValue >= 0) { int dPadValue = dPadRawValue / 4500; switch (dPadValue) { case 0: gamePadState.Buttons |= GamePadButton.PadUp; break; case 1: gamePadState.Buttons |= GamePadButton.PadUp; gamePadState.Buttons |= GamePadButton.PadRight; break; case 2: gamePadState.Buttons |= GamePadButton.PadRight; break; case 3: gamePadState.Buttons |= GamePadButton.PadRight; gamePadState.Buttons |= GamePadButton.PadDown; break; case 4: gamePadState.Buttons |= GamePadButton.PadDown; break; case 5: gamePadState.Buttons |= GamePadButton.PadDown; gamePadState.Buttons |= GamePadButton.PadLeft; break; case 6: gamePadState.Buttons |= GamePadButton.PadLeft; break; case 7: gamePadState.Buttons |= GamePadButton.PadLeft; gamePadState.Buttons |= GamePadButton.PadUp; break; } } // Left Thumb gamePadState.LeftThumb = new Vector2(2.0f * (joystickState.X / 65535.0f - 0.5f), -2.0f * (joystickState.Y / 65535.0f - 0.5f)); gamePadState.LeftThumb.X = ClampDeadZone(gamePadState.LeftThumb.X, GamePadAxisDeadZone); gamePadState.LeftThumb.Y = ClampDeadZone(gamePadState.LeftThumb.Y, GamePadAxisDeadZone); // Right Thumb gamePadState.RightThumb = new Vector2(2.0f * (joystickState.Z / 65535.0f - 0.5f), -2.0f * (joystickState.RotationZ / 65535.0f - 0.5f)); gamePadState.RightThumb.X = ClampDeadZone(gamePadState.RightThumb.X, GamePadAxisDeadZone); gamePadState.RightThumb.Y = ClampDeadZone(gamePadState.RightThumb.Y, GamePadAxisDeadZone); return(gamePadState); }
public void CaptureJoysticks() { // Initialize DirectInput var directInput = new DirectInput(); // Find all joysticks connected to the system IList<DeviceInstance> connectedJoysticks = new List<DeviceInstance>(); // - look for gamepads foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)) { connectedJoysticks.Add(deviceInstance); } // - look for joysticks foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) { connectedJoysticks.Add(deviceInstance); } // Use the two first joysticks found if (connectedJoysticks.Count >= 1) { joystick1 = new Joystick(directInput, connectedJoysticks[0].InstanceGuid); Joystick1DeviceName = connectedJoysticks[0].InstanceName; joystick1.Acquire(); } if (connectedJoysticks.Count >= 2) { joystick2 = new Joystick(directInput, connectedJoysticks[1].InstanceGuid); Joystick2DeviceName = connectedJoysticks[1].InstanceName; joystick2.Acquire(); } }