public DirectInputGamePad(DirectInput directInput, GamePadKey key) : base(key) { this.key = key; this.directInput = directInput; this.instance = new Joystick(directInput, key.Guid); joystickState = new JoystickState(); }
public MainWindow() { InitializeComponent(); createNewTimer(); oldgstate = GamePad.GetState(activeGamepad); oldjstate = Joystick.GetState(activeJoystick); }
public static DirectXControllerFunction Create(DirectXControllerInterface controllerInterface, Guid objectType, int objectNumber, JoystickState initialState) { DirectXControllerFunction function = null; if (objectType == ObjectGuid.Button) function = new DirectXControllerButton(controllerInterface, objectNumber, initialState); else if (objectType == ObjectGuid.Slider) function = new DirectXControllerAxis(controllerInterface, DirectXControllerAxis.AxisType.Slider, objectNumber, initialState); else if (objectType == ObjectGuid.XAxis) function = new DirectXControllerAxis(controllerInterface, DirectXControllerAxis.AxisType.X, objectNumber, initialState); else if (objectType == ObjectGuid.YAxis) function = new DirectXControllerAxis(controllerInterface, DirectXControllerAxis.AxisType.Y, objectNumber, initialState); else if (objectType == ObjectGuid.ZAxis) function = new DirectXControllerAxis(controllerInterface, DirectXControllerAxis.AxisType.Z, objectNumber, initialState); else if (objectType == ObjectGuid.RxAxis) function = new DirectXControllerAxis(controllerInterface, DirectXControllerAxis.AxisType.Rx, objectNumber, initialState); else if (objectType == ObjectGuid.RyAxis) function = new DirectXControllerAxis(controllerInterface, DirectXControllerAxis.AxisType.Ry, objectNumber, initialState); else if (objectType == ObjectGuid.RzAxis) function = new DirectXControllerAxis(controllerInterface, DirectXControllerAxis.AxisType.Rz, objectNumber, initialState); else if (objectType == ObjectGuid.PovController) function = new DirectXControllerPOVHat(controllerInterface, objectNumber, initialState); return function; }
// TODO: allow user to configure the action based on value (vibrato, pitch shift, etc.) /// <summary> /// Emulates behaviour like that of <see cref="JoystickState.GetButtons()"/>. /// </summary> /// /// <param name="state"> /// The <see cref="JoystickState"/> instance to query. /// </param> /// /// <returns> /// An array of integers representing the values of the respective axes. /// </returns> /// /// <remarks> /// The irony here is that the value are probably read from an array in the first place. /// </remarks> public static int[] GetValues(JoystickState state) { int[] result = new int[] { state.ARx, state.ARy, state.ARz, state.AX, state.AY, state.AZ, state.FRx, state.FRy, state.FRz, state.FX, state.FY, state.FZ, state.Rx, state.Ry, state.Rz, state.VRx, state.VRy, state.VRz, state.VX, state.VY, state.VZ, state.X, state.Y, state.Z, }; return result; }
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(); } }
//Function of initialize device public static void InitDevices() { //create joystick device. foreach (DeviceInstance di in Manager.GetDevices( DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly)) { joystick = new Device(di.InstanceGuid); break; } if (joystick == null) { //Throw exception if joystick not found. } //Set joystick axis ranges. else { foreach (DeviceObjectInstance doi in joystick.Objects) { if ((doi.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0) { joystick.Properties.SetRange( ParameterHow.ById, doi.ObjectId, new InputRange(-5000, 5000)); } } joystick.Properties.AxisModeAbsolute = true; joystick.SetCooperativeLevel(null,CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background); //Acquire devices for capturing. joystick.Acquire(); state = joystick.CurrentJoystickState; } }
private int clockspeed = 25; // 25 millisecond window for clock on joystick polling. public ControllerEngine() { this.ActiveDevice = 0; oldgstate = GamePad.GetState(this.ActiveDevice); oldjstate = Joystick.GetState(this.ActiveDevice); createNewTimer(); }
public bool[][] buttons = new bool[3][]; //2D-array, 1.dim = joystick, 2.dim = button public JoystickHandler() { getSticks(); sticks = getSticks(); state = new JoystickState(); joystickDialog = new JoystickConfig(); }
public static unsafe void Update(int index, int[] analogData, byte[] digitalData) { //Create the structure var state = new JoystickState(); state.Signature = (uint)0x53544143; state.NumAnalog = (char)63; state.NumDigital = (char)128; state.Analog = new int[state.NumAnalog]; state.Digital = new char[state.NumDigital]; //Fill it with our data if (analogData != null) Array.Copy(analogData, 0, state.Analog, 0, Math.Min(analogData.Length, state.Analog.Length)); if (digitalData != null) Array.Copy(digitalData, 0, state.Digital, 0, Math.Min(digitalData.Length, state.Digital.Length)); //Send the data uint bytesReturned = 0; NativeOverlapped overlapped = new NativeOverlapped(); var h = _GetHandle(index); bool ret = DeviceIoControl(h, 0x00220000, state, (uint)Marshal.SizeOf(state), IntPtr.Zero, 0, ref bytesReturned, ref overlapped); if (!ret) { //TODO: Do something with this? int lastError = Marshal.GetLastWin32Error(); //Invalidate the handle _CloseHandle(h); _handles[index] = null; } }
internal static JoystickState NormalizeInput(short X, short Y, short inputDeadZone, short joystickRange) { //From http://msdn.microsoft.com/en-us/library/windows/desktop/ee417001(v=vs.85).aspx JoystickState result = new JoystickState(); //determine how far the controller is pushed result.Magnitude = (float)Math.Sqrt(X * X + Y * Y); //determine the direction the controller is pushed result.NormalizedX = X / result.Magnitude; result.NormalizedY = Y / result.Magnitude; result.NormalizedMagnitude = 0; //check if the controller is outside a circular dead zone if (result.Magnitude > inputDeadZone) { //clip the magnitude at its expected maximum value if (result.Magnitude > joystickRange) result.Magnitude = joystickRange; //adjust magnitude relative to the end of the dead zone result.Magnitude -= inputDeadZone; //optionally normalize the magnitude with respect to its expected range //giving a magnitude value of 0.0 to 1.0 result.NormalizedMagnitude = result.Magnitude / (joystickRange - inputDeadZone); } else //if the controller is in the deadzone zero out the magnitude { result.Magnitude = 0; result.NormalizedMagnitude = 0; } return result; }
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); }
public void Poll() { this.device.Poll(); this.state = this.device.CurrentJoystickState; byte[] newButtons = this.state.GetButtons(); if (this.buttons == null) { this.buttons = newButtons; this.HasButtonStateChanged = true; return; } this.IsButtonPressed = false; this.HasButtonStateChanged = false; for (int i = 0; i < newButtons.Length; i++) { if (newButtons[i] != this.buttons[i]) { this.HasButtonStateChanged = true; } if (newButtons[i] > 0) { this.IsButtonPressed = true; } } if (this.HasButtonStateChanged) { this.buttons = newButtons; } }
public JoystickState GetState(int index) { XInputState xstate; XInputErrorCode error = xinput.GetState((XInputUserIndex)index, out xstate); JoystickState state = new JoystickState(); if (error == XInputErrorCode.Success) { state.SetIsConnected(true); state.SetAxis(JoystickAxis.Axis0, (short)xstate.GamePad.ThumbLX); state.SetAxis(JoystickAxis.Axis1, (short)Math.Min(short.MaxValue, -xstate.GamePad.ThumbLY)); state.SetAxis(JoystickAxis.Axis2, (short)Common.HidHelper.ScaleValue(xstate.GamePad.LeftTrigger, 0, byte.MaxValue, short.MinValue, short.MaxValue)); state.SetAxis(JoystickAxis.Axis3, (short)xstate.GamePad.ThumbRX); state.SetAxis(JoystickAxis.Axis4, (short)Math.Min(short.MaxValue, -xstate.GamePad.ThumbRY)); state.SetAxis(JoystickAxis.Axis5, (short)Common.HidHelper.ScaleValue(xstate.GamePad.RightTrigger, 0, byte.MaxValue, short.MinValue, short.MaxValue)); state.SetButton(JoystickButton.Button0, (xstate.GamePad.Buttons & XInputButtons.A) != 0); state.SetButton(JoystickButton.Button1, (xstate.GamePad.Buttons & XInputButtons.B) != 0); state.SetButton(JoystickButton.Button2, (xstate.GamePad.Buttons & XInputButtons.X) != 0); state.SetButton(JoystickButton.Button3, (xstate.GamePad.Buttons & XInputButtons.Y) != 0); state.SetButton(JoystickButton.Button4, (xstate.GamePad.Buttons & XInputButtons.LeftShoulder) != 0); state.SetButton(JoystickButton.Button5, (xstate.GamePad.Buttons & XInputButtons.RightShoulder) != 0); state.SetButton(JoystickButton.Button6, (xstate.GamePad.Buttons & XInputButtons.Back) != 0); state.SetButton(JoystickButton.Button7, (xstate.GamePad.Buttons & XInputButtons.Start) != 0); state.SetButton(JoystickButton.Button8, (xstate.GamePad.Buttons & XInputButtons.LeftThumb) != 0); state.SetButton(JoystickButton.Button9, (xstate.GamePad.Buttons & XInputButtons.RightThumb) != 0); state.SetButton(JoystickButton.Button10, (xstate.GamePad.Buttons & XInputButtons.Guide) != 0); state.SetHat(JoystickHat.Hat0, new JoystickHatState(TranslateHat(xstate.GamePad.Buttons))); } return state; }
public string Tick() { _currentState = Joystick.GetState(_joystickIndex); var sb = new StringBuilder(); for (int i = 0; i < 4; i++) { sb.AppendLine(GetAxisText((JoystickAxis)i)); } for (int i = 0; i < 1; i++) { sb.AppendLine(GetButtonText((JoystickButton)i)); } var panAxis = ReadAxis(JoystickAxis.Axis0); var tiltAxis = (ReadAxis(JoystickAxis.Axis1) -0.5m) * 2; // tilt normalisation var throttleAxis = ReadAxis(JoystickAxis.Axis3); var moveStrategy = new JoystickModifierStrategy(panAxis, tiltAxis, throttleAxis); var newPosition = moveStrategy.CalculateNewSetting(CurrentSetting); MoveAbsolute(newPosition); sb.AppendFormat("Pan Tilt = {0}\r\n", newPosition); return sb.ToString(); }
public DirectXControllerAxis(DirectXControllerInterface controllerInterface, AxisType type, int axisNumber, JoystickState initialState) { _axisType = type; _axisNumber = axisNumber; _value = new HeliosValue(controllerInterface, new BindingValue(GetValue(initialState)), "", Name, "Current value for " + Name + ".", "(0 - 65536)", BindingValueUnits.Numeric); _triggers.Add(_value); }
/// <summary>Retrieves the current value of the axis</summary> /// <param name="gamePadState">Game pad state that will receive the value</param> /// <param name="joystickState">State from which the axis is retrieved</param> public void Convert( FlatGamePadState gamePadState, ref JoystickState joystickState ) { if (joystickState.X < base.Center) { gamePadState.LeftThumbStick.X = (float)(base.Center - joystickState.X) / base.Min; } else { gamePadState.LeftThumbStick.X = (float)(joystickState.X - base.Center) / base.Max; } }
public override void Update(GameTime gameTime) { base.Update(gameTime); _joyState = Application.InputManager.GetJoystickState(Index); // Mapping // TODO Joypad mapping // End _previousJoystate = _joyState; }
public double GetValue(JoystickState joystickState, int povIndex) { // Position is quantized degrees from North quantized to the four cardinal directions. int position = joystickState.GetPointOfViewControllers()[povIndex]; foreach(Range range in _directionRanges) { if(range.Contains(position)) { return range.Value / 100d; } } return -1; }
/// <summary>Retrieves the current value of the axis</summary> /// <param name="state">Joystick state the axis is taken from</param> /// <returns>The value of the axis in the joystick state</returns> public float GetValue(ref JoystickState state) { int raw = Read(ref state); if (raw < this.center) { return (float) (this.center - raw)/this.min; } else { return (float) (raw - this.center)/this.max; } }
public void Update() { if (_device.Acquire().IsFailure) return; if (_device.Poll().IsFailure) return; if (_type == DeviceType.Keyboard) _keyboardState = ((Keyboard) _device).GetCurrentState(); else if (_type == DeviceType.Joystick) _joystickState = ((Joystick) _device).GetCurrentState(); }
public DirectXControllerButton(DirectXControllerInterface controllerInterface, int buttonNumber, JoystickState initialState) { _buttonNumber = buttonNumber; _name = "Button " + (_buttonNumber + 1); _value = new HeliosValue(controllerInterface, new BindingValue(GetValue(initialState)), "", _name, "Current state for " + _name + ".", "True if pressed, false other wise.", BindingValueUnits.Boolean); _press = new HeliosTrigger(controllerInterface, "", _name, "pressed", "Fires when " + _name + " is pressed.", "Always returns true.", BindingValueUnits.Boolean); _release = new HeliosTrigger(controllerInterface, "", _name, "released", "Fires when " + _name + " is released.", "Always returns false.", BindingValueUnits.Boolean); _triggers.Add(_press); _triggers.Add(_release); _lastPollValue = GetValue(initialState); }
private bool UpdateState() { try { if (!IsConnected) device.Acquire(); currentState = device.GetCurrentState(); } catch (SharpDX.SharpDXException) { currentState = null; } return currentState != null; }
private void Poll() { if (_joystick == null) return; try { _joystick.Poll(); _state = _joystick.GetCurrentState(); } catch (Exception ex) { Logger.LogExceptionToFile(ex); } }
public void Poll(Action<JoystickState> f) { if (joystick.Acquire().IsFailure) return; if (joystick.Poll().IsFailure) return; joyState = joystick.GetCurrentState(); if (Result.Last.IsFailure) return; // Joystick is all good, call the function f(joyState); }
public override void Initialize() { buttonDown = -1; joystickIsReady = false; // Make sure that DirectInput has been initialized DirectInput dinput = new DirectInput(); state = new JoystickState(); // 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(Core.Settings.RenderForm.Handle, CooperativeLevel.Exclusive | CooperativeLevel.Foreground); break; } catch (DirectInputException) { } } if (joystick != null) { foreach (DeviceObjectInstance deviceObject in joystick.GetObjects()) { if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0) joystick.GetObjectPropertiesById((int)deviceObject.ObjectType).SetRange(-1000, 1000); } } else { return; } // acquire the device joystick.Acquire(); timer = new Timer(); timer.Interval = 1000 / 10; timer.Tick += new EventHandler(timer_Tick); timer.Start(); }
protected override void ProcessController() { ControllerState newState = new ControllerState(); JoystickState joyState = new JoystickState(); if (this.padsList == null || !this.padsList.Any()) { this.padsList = this.GetGamePads(); if (!this.padsList.Any()) return; } if (this.device == null) { this.device = this.padsList[0]; } if (this.pad == null) { this.Acquire(); } if (this.pad == null || this.pad.Poll().IsFailure || this.pad.GetCurrentState(ref joyState).IsFailure) { newState.Active = false; } else { //var objs = pad.GetObjects(); newState.Active = true; newState.X = (joyState.X / 5000d); newState.Y = (joyState.Y / 5000d); newState.Buttons = joyState.GetButtons(); } if (!newState.Equals(this.State)) { this.State = newState; if (this.OnUpdate != null) { this.OnUpdate.Invoke(this.State); } } }
public void PollChanges(iGameClient GameCli) { //polls changes in this controller from the previous poll and raises //appropriate events in iGameClient depending on the differences. if (!haspolled) { haspolled=true; ourdevice.Poll(); laststate = ourdevice.CurrentJoystickState; return; } laststate = ourdevice.CurrentJoystickState; ourdevice.Poll(); byte[] prevbuttons = laststate.GetButtons(); byte[] currbuttons = ourdevice.CurrentJoystickState.GetButtons(); }
byte[] Rumble = new byte[8]; //who cares, just compatibility public Form1() { directInput = new DirectInput(); x360Bus = new DS4Windows.X360Device(); runningController = null; runningControllerGuid = Guid.Empty; joystick = null; lastState = null; updateThread = null; aquired = false; xbus_opened = false; xinput_plugged = false; Array.Clear(xinputData, 0, xinputData.Length); xinput_as_360_buttons = false; InitializeComponent(); }
public void Update() { try { if (joystick.Acquire().IsFailure) return; } catch { return; } if (joystick.Poll().IsFailure) return; state = joystick.GetCurrentState(); if (Result.Last.IsFailure) // do something? return; }
public DirectInputState(JoystickState state) { // Fill axis. Axis = new int[] { state.X, state.Y, state.Z, state.RotationX, state.RotationY, state.RotationZ, state.AccelerationX, state.AccelerationY, state.AccelerationZ, state.AngularAccelerationX, state.AngularAccelerationY, state.AngularAccelerationZ, state.ForceX, state.ForceY, state.ForceZ, state.TorqueX, state.TorqueY, state.TorqueZ, state.VelocityX, state.VelocityY, state.VelocityZ, state.AngularVelocityX, state.AngularVelocityY, state.AngularVelocityZ, }; // Fill Sliders. List<int> sl = new List<int>(); sl.AddRange(state.Sliders); sl.AddRange(state.AccelerationSliders); sl.AddRange(state.ForceSliders); sl.AddRange(state.VelocitySliders); Sliders = sl.ToArray(); // Fill POVs. Pows = state.PointOfViewControllers.ToArray(); // Fill buttons. Buttons = state.Buttons.ToArray(); }
public void tポーリング(bool bWindowがアクティブ中, bool bバッファ入力を使用する) { #region [ bButtonフラグ初期化 ] for (int i = 0; i < 256; i++) { this.bButtonPushDown[i] = false; this.bButtonPullUp[i] = false; } #endregion if ((bWindowがアクティブ中 && !this.devJoystick.Acquire().IsFailure) && !this.devJoystick.Poll().IsFailure) { // this.list入力イベント = new List<STInputEvent>( 32 ); this.list入力イベント.Clear(); // #xxxxx 2012.6.11 yyagi; To optimize, I removed new(); if (bバッファ入力を使用する) { #region [ a.バッファ入力 ] //----------------------------- var length = this.devJoystick.GetDeviceData(_rawBufferedDataArray, false); if (!Result.Last.IsSuccess) { return; } for (int i = 0; i < length; i++) { var rawBufferedData = _rawBufferedDataArray[i]; switch (rawBufferedData.Offset) { case 0: #region [ X軸- ] //----------------------------- bButtonUpDown(rawBufferedData, rawBufferedData.Data, 0, 1); //----------------------------- #endregion #region [ X軸+ ] //----------------------------- bButtonUpDown(rawBufferedData, rawBufferedData.Data, 1, 0); //----------------------------- #endregion break; case 4: #region [ Y軸- ] //----------------------------- bButtonUpDown(rawBufferedData, rawBufferedData.Data, 2, 3); //----------------------------- #endregion #region [ Y軸+ ] //----------------------------- bButtonUpDown(rawBufferedData, rawBufferedData.Data, 3, 2); #endregion break; case 8: #region [ Z軸- ] //----------------------------- bButtonUpDown(rawBufferedData, rawBufferedData.Data, 4, 5); //----------------------------- #endregion #region [ Z軸+ ] //----------------------------- bButtonUpDown(rawBufferedData, rawBufferedData.Data, 5, 4); #endregion break; case 32: const int p = 0; // const until we support more than one POV hat int nPovDegree = rawBufferedData.Data; int nWay = (nPovDegree + 2250) / 4500; if (nWay == 8) { nWay = 0; } STInputEvent e = new STInputEvent(); if (nPovDegree == -1 || nPovDegree == 0xFFFF) { e.nKey = 6 + 128 + this.nPovState[p]; this.nPovState[p] = -1; e.b押された = false; this.bButtonState[e.nKey] = false; this.bButtonPullUp[e.nKey] = true; } else { this.nPovState[p] = nWay; e.nKey = 6 + 128 + nWay; e.b押された = true; this.bButtonState[e.nKey] = true; this.bButtonPushDown[e.nKey] = true; } e.nTimeStamp = CSound管理.rc演奏用タイマ.nサウンドタイマーのシステム時刻msへの変換(rawBufferedData.Timestamp); this.list入力イベント.Add(e); break; default: var buttonIndex = rawBufferedData.Offset - 48; if (-1 < buttonIndex && buttonIndex < 32) { var key = 6 + buttonIndex; var wasPressed = (rawBufferedData.Data & 128) == 128; STInputEvent item = new STInputEvent() { nKey = key, b押された = wasPressed, nTimeStamp = CSound管理.rc演奏用タイマ.nサウンドタイマーのシステム時刻msへの変換(rawBufferedData.Timestamp), }; this.list入力イベント.Add(item); this.bButtonState[item.nKey] = wasPressed; this.bButtonPushDown[item.nKey] = wasPressed; this.bButtonPullUp[item.nKey] = !wasPressed; } break; } } //----------------------------- #endregion } else { #region [ b.状態入力 ] //----------------------------- JoystickState currentState = this.devJoystick.GetCurrentState(); if (Result.Last.IsSuccess && currentState != null) { #region [ X軸- ] //----------------------------- if (currentState.X < -500) { if (this.bButtonState[0] == false) { STInputEvent ev = new STInputEvent() { nKey = 0, b押された = true, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[0] = true; this.bButtonPushDown[0] = true; } } else { if (this.bButtonState[0] == true) { STInputEvent ev = new STInputEvent() { nKey = 0, b押された = false, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[0] = false; this.bButtonPullUp[0] = true; } } //----------------------------- #endregion #region [ X軸+ ] //----------------------------- if (currentState.X > 500) { if (this.bButtonState[1] == false) { STInputEvent ev = new STInputEvent() { nKey = 1, b押された = true, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[1] = true; this.bButtonPushDown[1] = true; } } else { if (this.bButtonState[1] == true) { STInputEvent event7 = new STInputEvent() { nKey = 1, b押された = false, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(event7); this.bButtonState[1] = false; this.bButtonPullUp[1] = true; } } //----------------------------- #endregion #region [ Y軸- ] //----------------------------- if (currentState.Y < -500) { if (this.bButtonState[2] == false) { STInputEvent ev = new STInputEvent() { nKey = 2, b押された = true, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[2] = true; this.bButtonPushDown[2] = true; } } else { if (this.bButtonState[2] == true) { STInputEvent ev = new STInputEvent() { nKey = 2, b押された = false, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[2] = false; this.bButtonPullUp[2] = true; } } //----------------------------- #endregion #region [ Y軸+ ] //----------------------------- if (currentState.Y > 500) { if (this.bButtonState[3] == false) { STInputEvent ev = new STInputEvent() { nKey = 3, b押された = true, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[3] = true; this.bButtonPushDown[3] = true; } } else { if (this.bButtonState[3] == true) { STInputEvent ev = new STInputEvent() { nKey = 3, b押された = false, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[3] = false; this.bButtonPullUp[3] = true; } } //----------------------------- #endregion #region [ Z軸- ] //----------------------------- if (currentState.Z < -500) { if (this.bButtonState[4] == false) { STInputEvent ev = new STInputEvent() { nKey = 4, b押された = true, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[4] = true; this.bButtonPushDown[4] = true; } } else { if (this.bButtonState[4] == true) { STInputEvent ev = new STInputEvent() { nKey = 4, b押された = false, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[4] = false; this.bButtonPullUp[4] = true; } } //----------------------------- #endregion #region [ Z軸+ ] //----------------------------- if (currentState.Z > 500) { if (this.bButtonState[5] == false) { STInputEvent ev = new STInputEvent() { nKey = 5, b押された = true, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[5] = true; this.bButtonPushDown[5] = true; } } else { if (this.bButtonState[5] == true) { STInputEvent event15 = new STInputEvent() { nKey = 5, b押された = false, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(event15); this.bButtonState[5] = false; this.bButtonPullUp[5] = true; } } //----------------------------- #endregion #region [ ボタン ] //----------------------------- bool bIsButtonPressedReleased = false; bool[] buttons = currentState.GetButtons(); for (int j = 0; (j < buttons.Length) && (j < 128); j++) { if (this.bButtonState[6 + j] == false && buttons[j]) { STInputEvent item = new STInputEvent() { nKey = 6 + j, b押された = true, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(item); this.bButtonState[6 + j] = true; this.bButtonPushDown[6 + j] = true; bIsButtonPressedReleased = true; } else if (this.bButtonState[6 + j] == true && !buttons[j]) { STInputEvent item = new STInputEvent() { nKey = 6 + j, b押された = false, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(item); this.bButtonState[6 + j] = false; this.bButtonPullUp[6 + j] = true; bIsButtonPressedReleased = true; } } //----------------------------- #endregion // #24341 2011.3.12 yyagi: POV support #region [ POV HAT 4/8way (only single POV switch is supported)] int[] povs = currentState.GetPointOfViewControllers(); if (povs != null) { if (povs[0] >= 0) { int nPovDegree = povs[0]; int nWay = (nPovDegree + 2250) / 4500; if (nWay == 8) { nWay = 0; } if (this.bButtonState[6 + 128 + nWay] == false) { STInputEvent stevent = new STInputEvent() { nKey = 6 + 128 + nWay, //Debug.WriteLine( "POVS:" + povs[ 0 ].ToString( CultureInfo.CurrentCulture ) + ", " +stevent.nKey ); b押された = true, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(stevent); this.bButtonState[stevent.nKey] = true; this.bButtonPushDown[stevent.nKey] = true; } } else if (bIsButtonPressedReleased == false) // #xxxxx 2011.12.3 yyagi 他のボタンが何も押され/離されてない=POVが離された { int nWay = 0; for (int i = 6 + 0x80; i < 6 + 0x80 + 8; i++) { // 離されたボタンを調べるために、元々押されていたボタンを探す。 if (this.bButtonState[i] == true) // DirectInputを直接いじるならこんなことしなくて良いのに、あぁ面倒。 { // この処理が必要なために、POVを1個しかサポートできない。無念。 nWay = i; break; } } if (nWay != 0) { STInputEvent stevent = new STInputEvent() { nKey = nWay, b押された = false, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(stevent); this.bButtonState[nWay] = false; this.bButtonPullUp[nWay] = true; } } } #endregion } //----------------------------- #endregion } } }
public void poll() { this.state = Joystick.GetState(this.joystickIndex); }
/// <summary> /// Reads the input from the controller. /// </summary> internal override void ReadInput() { JoystickState joystick = Joystick.GetState(joystickIndex); PowerNotchesEnum powerNotch = PowerNotchesEnum.None; BrakeNotchesEnum brakeNotch = BrakeNotchesEnum.None; powerNotch = joystick.IsButtonDown(ButtonIndex.Power1) ? powerNotch | PowerNotchesEnum.Power1 : powerNotch & ~PowerNotchesEnum.Power1; brakeNotch = joystick.IsButtonDown(ButtonIndex.Brake1) ? brakeNotch | BrakeNotchesEnum.Brake1 : brakeNotch & ~BrakeNotchesEnum.Brake1; brakeNotch = joystick.IsButtonDown(ButtonIndex.Brake2) ? brakeNotch | BrakeNotchesEnum.Brake2 : brakeNotch & ~BrakeNotchesEnum.Brake2; brakeNotch = joystick.IsButtonDown(ButtonIndex.Brake3) ? brakeNotch | BrakeNotchesEnum.Brake3 : brakeNotch & ~BrakeNotchesEnum.Brake3; brakeNotch = joystick.IsButtonDown(ButtonIndex.Brake4) ? brakeNotch | BrakeNotchesEnum.Brake4 : brakeNotch & ~BrakeNotchesEnum.Brake4; if (UsesAxis) { // The adapter uses an axis to map the direction buttons. // This is the case of some PlayStation adapters. powerNotch = joystick.GetAxis(AxisIndex) < -0.5 ? powerNotch | PowerNotchesEnum.Power2 : powerNotch & ~PowerNotchesEnum.Power2; powerNotch = joystick.GetAxis(AxisIndex) > 0.5 ? powerNotch | PowerNotchesEnum.Power3 : powerNotch & ~PowerNotchesEnum.Power3; } else if (UsesHat) { // The adapter uses the hat to map the direction buttons. // This is the case of some PlayStation adapters. powerNotch = joystick.GetHat((JoystickHat)HatIndex).IsLeft ? powerNotch | PowerNotchesEnum.Power2 : powerNotch & ~PowerNotchesEnum.Power2; powerNotch = joystick.GetHat((JoystickHat)HatIndex).IsRight ? powerNotch | PowerNotchesEnum.Power3 : powerNotch & ~PowerNotchesEnum.Power3; } else { // The adapter maps the direction buttons to independent buttons. powerNotch = joystick.IsButtonDown(ButtonIndex.Power2) ? powerNotch | PowerNotchesEnum.Power2 : powerNotch & ~PowerNotchesEnum.Power2; powerNotch = joystick.IsButtonDown(ButtonIndex.Power3) ? powerNotch | PowerNotchesEnum.Power3 : powerNotch & ~PowerNotchesEnum.Power3; } if ((UsesHat || UsesAxis) && powerNotch == PowerNotchesEnum.P4) { // Hack for adapters using a hat/axis where pressing left and right simultaneously reports only left being pressed if (InputTranslator.PreviousPowerNotch < InputTranslator.PowerNotches.P3) { InputTranslator.PowerNotch = InputTranslator.PowerNotches.N; } else { InputTranslator.PowerNotch = InputTranslator.PowerNotches.P4; } } else if ((UsesHat || UsesAxis) && powerNotch == PowerNotchesEnum.Transition) { // Hack for adapters using a hat/axis where pressing left and right simultaneously reports nothing being pressed, the same as the transition state // Has the side effect of the power notch jumping P1>N>P2, but it is barely noticeable unless moving the handle very slowly if (InputTranslator.PreviousPowerNotch < InputTranslator.PowerNotches.P2) { InputTranslator.PowerNotch = InputTranslator.PowerNotches.N; } } else if (powerNotch != PowerNotchesEnum.Transition) { // Set notch only if it is not a transition InputTranslator.PowerNotch = PowerNotchMap[powerNotch]; } if (brakeNotch != BrakeNotchesEnum.Transition && (brakeNotch == BrakeNotchesEnum.Emergency || brakeNotch >= BrakeNotchesEnum.B8)) { // Set notch only if it is not a transition nor an unmarked notch InputTranslator.BrakeNotch = BrakeNotchMap[brakeNotch]; } InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.Select] = joystick.GetButton(ButtonIndex.Select); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.Start] = joystick.GetButton(ButtonIndex.Start); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.A] = joystick.GetButton(ButtonIndex.A); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.B] = joystick.GetButton(ButtonIndex.B); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.C] = joystick.GetButton(ButtonIndex.C); }
public bool UpdateVJD(UInt32 rID, ref JoystickState pData) { return(_UpdateVJD(rID, ref pData)); }
private void updateDevice(ref JoystickCapabilities caps, ref JoystickState state, ref JoystickState defaultState) { for (int i = 0; i < JoyKey.Count; i++) { buttons[i] = false; } List <Keys> Current = new List <Keys>(JoyKey.Count); for (int i = 0; i < caps.ButtonCount; i++) { if (state.IsButtonDown((JoystickButton)((int)JoystickButton.Button0 + i))) { buttons[i] = true; Current.Add((Keys)((int)JoyKey.Button0 + i)); } } for (int i = 0; i < caps.AxisCount; i++) { JoystickAxis axis = (JoystickAxis)(i + (int)JoystickAxis.Axis0); float axisState = state.GetAxis(axis); float defaultAxisState = defaultState.GetAxis(axis); // find the dead zone base value by rounding the default state to the nearest deadZoneRound float deadZoneBase = (float)Math.Round(defaultAxisState / deadZoneRound) * deadZoneRound; // the min/max input thresholds are a fractional value between the deadZoneBase value and the min/max value float inputThresholdMin = deadZoneBase + (-1 - deadZoneBase) * inputThresholdFraction; float inputThresholdMax = deadZoneBase + (1 - deadZoneBase) * inputThresholdFraction; if (Math.Abs(axisState - deadZoneBase) < deadZone) { } else if (axisState < inputThresholdMin) { int key = (int)JoyKey.AxisXMin + i * 2; buttons[key - (int)JoyKey.Button0] = true; Current.Add((Keys)key); } else if (axisState > inputThresholdMax) { int key = (int)JoyKey.AxisXMin + i * 2 + 1; buttons[key - (int)JoyKey.Button0] = true; Current.Add((Keys)key); } } // WORKAROUND: HatCount is incorrectly reported as 0 for XInput controllers, so always try at least 1 hat for (int i = 0; i < Math.Max(1, caps.HatCount); i++) { JoystickHatState hatState = state.GetHat((JoystickHat)(i + (int)JoystickHat.Hat0)); if (hatState.IsUp) { int key = (int)JoyKey.Hat0U + i * 4; buttons[key - (int)JoyKey.Button0] = true; Current.Add((Keys)key); } if (hatState.IsRight) { int key = (int)JoyKey.Hat0U + i * 4 + 1; buttons[key - (int)JoyKey.Button0] = true; Current.Add((Keys)key); } if (hatState.IsDown) { int key = (int)JoyKey.Hat0U + i * 4 + 2; buttons[key - (int)JoyKey.Button0] = true; Current.Add((Keys)key); } if (hatState.IsLeft) { int key = (int)JoyKey.Hat0U + i * 4 + 3; buttons[key - (int)JoyKey.Button0] = true; Current.Add((Keys)key); } } if (OnButtonDown != null) { if (Current.Count > 0) { OnButtonDown(null, Current); } } if (OnButtonPressed != null) { List <Keys> down = new List <Keys>(JoyKey.Count); for (int i = 0; i < JoyKey.Count; i++) { // release if (lastButtons[i] && !buttons[i]) { down.Add((Keys)((int)JoyKey.Button0 + i)); } } if (down.Count > 0) { OnButtonPressed(null, down); } } LastKeyDown.Clear(); LastKeyDown.AddRange(KeyDown); KeyDown.Clear(); KeyDown.AddRange(Current); buttons.CopyTo(lastButtons, 0); }
public void Reset() { state = null; }
private void SendActions(JoystickState state) { int actionCode = -1; int actionParam = -1; int curAxisValue = 0; // todo: timer stuff!! // buttons first! byte[] buttons = state.GetButtons(); int button = 0; string pressedButtons = ""; // button combos string sep = ""; foreach (byte b in buttons) { if (0 != (b & 0x80)) { pressedButtons += sep + button.ToString("00"); sep = ","; } button++; } if ((ButtonComboKill != "") && (ButtonComboKill == pressedButtons)) { if (null != _lastProc) { actionCode = (int)joyButton.comboKillProcess; actionParam = _lastProc.Id; } } else if ((ButtonComboClose != "") && (ButtonComboClose == pressedButtons)) { if (null != _lastProc) { actionCode = (int)joyButton.comboCloseProcess; actionParam = _lastProc.Id; } } // single buttons if (actionCode == -1) { button = 0; bool foundButton = false; foreach (byte b in buttons) { if (0 != (b & 0x80)) { foundButton = true; break; } button++; } if (foundButton) { if ((button >= 0) && (button <= 19)) { // don't need no stinkin' enum-constants here.... actionCode = 3030 + button; } } } // pov next if (actionCode == -1) { int[] pov = state.GetPointOfView(); switch (pov[0]) { case 0: { actionCode = (int)joyButton.povN; break; } case 9000: { actionCode = (int)joyButton.povE; break; } case 18000: { actionCode = (int)joyButton.povS; break; } case 27000: { actionCode = (int)joyButton.povW; break; } } } if (actionCode == -1) { // axes next if (Math.Abs(state.X) > _axisLimit) { curAxisValue = state.X; if (state.X > 0) { actionCode = (int)joyButton.axisXUp; // right } else { actionCode = (int)joyButton.axisXDown; // left } } else if (Math.Abs(state.Y) > _axisLimit) { curAxisValue = state.Y; if (state.Y > 0) { // down actionCode = (int)joyButton.axisYUp; } else { // up actionCode = (int)joyButton.axisYDown; } } else if (Math.Abs(state.Z) > _axisLimit) { curAxisValue = state.Z; if (state.Z > 0) { actionCode = (int)joyButton.axisZUp; } else { actionCode = (int)joyButton.axisZDown; } } } if (actionCode == -1) { // rotation if (Math.Abs(state.Rx) > _axisLimit) { curAxisValue = state.Rx; if (state.Rx > 0) { actionCode = (int)joyButton.rotationXUp; } else { actionCode = (int)joyButton.rotationXDown; } } else if (Math.Abs(state.Ry) > _axisLimit) { curAxisValue = state.Ry; if (state.Ry > 0) { actionCode = (int)joyButton.rotationYUp; } else { actionCode = (int)joyButton.rotationYDown; } } else if (Math.Abs(state.Rz) > _axisLimit) { curAxisValue = state.Rz; if (state.Rz > 0) { actionCode = (int)joyButton.rotationZUp; } else { actionCode = (int)joyButton.rotationZDown; } } } if (VerifyAction(actionCode, curAxisValue)) { Log.Info("mapping action {0}", actionCode); _inputHandler.MapAction(actionCode, actionParam); } }
protected override double _GetValue(JoystickState joystickState) { return(joystickState.RotationY); }
/// <summary> /// Reads the input from the controller. /// </summary> internal override void ReadInput() { JoystickState joystick = Joystick.GetState(joystickIndex); double brakeAxis = Math.Round(joystick.GetAxis(0), 4); double powerAxis = Math.Round(joystick.GetAxis(1), 4); for (int i = 0; i < brakeBytes.Length; i += 2) { // Each notch uses two bytes, minimum value and maximum value if (brakeAxis >= GetAxisValue(brakeBytes[i]) && brakeAxis <= GetAxisValue(brakeBytes[i + 1])) { if (brakeBytes.Length == i + 2) { // Last notch should be Emergency InputTranslator.BrakeNotch = InputTranslator.BrakeNotches.Emergency; } else { // Regular brake notch InputTranslator.BrakeNotch = (InputTranslator.BrakeNotches)(i / 2); } break; } } for (int i = 0; i < powerBytes.Length; i += 2) { // Each notch uses two bytes, minimum value and maximum value if (powerAxis >= GetAxisValue(powerBytes[i]) && powerAxis <= GetAxisValue(powerBytes[i + 1])) { InputTranslator.PowerNotch = (InputTranslator.PowerNotches)(i / 2); break; } } InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.Select] = joystick.GetButton(buttonIndex[(int)InputTranslator.ControllerButton.Select]); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.Start] = joystick.GetButton(buttonIndex[(int)InputTranslator.ControllerButton.Start]); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.A] = joystick.GetButton(buttonIndex[(int)InputTranslator.ControllerButton.A]); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.B] = joystick.GetButton(buttonIndex[(int)InputTranslator.ControllerButton.B]); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.C] = joystick.GetButton(buttonIndex[(int)InputTranslator.ControllerButton.C]); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.D] = joystick.GetButton(buttonIndex[(int)InputTranslator.ControllerButton.D]); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.LDoor] = joystick.GetButton(buttonIndex[(int)InputTranslator.ControllerButton.LDoor]); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.RDoor] = joystick.GetButton(buttonIndex[(int)InputTranslator.ControllerButton.RDoor]); if (Buttons.HasFlag(ControllerButtons.DPad)) { if (comboDpad) { // On some controllers, check for Select+A/B/C/D combo bool dPadUp = Convert.ToBoolean(joystick.GetButton(buttonIndex[(int)InputTranslator.ControllerButton.Select])) && Convert.ToBoolean(joystick.GetButton(buttonIndex[(int)InputTranslator.ControllerButton.D])); bool dPadDown = Convert.ToBoolean(joystick.GetButton(buttonIndex[(int)InputTranslator.ControllerButton.Select])) && Convert.ToBoolean(joystick.GetButton(buttonIndex[(int)InputTranslator.ControllerButton.B])); bool dPadLeft = Convert.ToBoolean(joystick.GetButton(buttonIndex[(int)InputTranslator.ControllerButton.Select])) && Convert.ToBoolean(joystick.GetButton(buttonIndex[(int)InputTranslator.ControllerButton.A])); bool dPadRight = Convert.ToBoolean(joystick.GetButton(buttonIndex[(int)InputTranslator.ControllerButton.Select])) && Convert.ToBoolean(joystick.GetButton(buttonIndex[(int)InputTranslator.ControllerButton.C])); bool dPadAny = dPadUp || dPadDown || dPadLeft || dPadRight; InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.Up] = (ButtonState)(dPadUp ? 1 : 0); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.Down] = (ButtonState)(dPadDown ? 1 : 0); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.Left] = (ButtonState)(dPadLeft ? 1 : 0); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.Right] = (ButtonState)(dPadRight ? 1 : 0); // Disable original buttons if necessary InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.Select] = InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.Select] ^ (ButtonState)(dPadAny ? 1 : 0); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.A] = InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.A] ^ (ButtonState)(dPadLeft ? 1 : 0); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.B] = InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.B] ^ (ButtonState)(dPadDown ? 1 : 0); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.C] = InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.C] ^ (ButtonState)(dPadRight ? 1 : 0); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.D] = InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.D] ^ (ButtonState)(dPadUp ? 1 : 0); } else { // On other controllers, read the first hat InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.Up] = (ButtonState)(joystick.GetHat(JoystickHat.Hat0).IsUp ? 1 : 0); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.Down] = (ButtonState)(joystick.GetHat(JoystickHat.Hat0).IsDown ? 1 : 0); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.Left] = (ButtonState)(joystick.GetHat(JoystickHat.Hat0).IsLeft ? 1 : 0); InputTranslator.ControllerButtons[(int)InputTranslator.ControllerButton.Right] = (ButtonState)(joystick.GetHat(JoystickHat.Hat0).IsRight ? 1 : 0); } } }
/// <summary> /// Update DirectInput control from DirectInput device. /// </summary> /// <param name="device">DirectInput device.</param> /// <returns>List of buttons/DPad pressed, axis/sliders turned.</returns> void ShowDirectInputState(JoystickState state) { if (state == null || state.Equals(oldState)) { return; } // 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; }
/// <summary> /// Update state of joystick /// </summary> public void Update() { //Get the state of the joystick JoystickState state = joystick.GetCurrentState(); //Save prev values for autodetection of axis Array.Copy(axis, axisPrev, axis.Length); //Update axes values axis[0] = state.AccelerationX; //Ax axis[1] = state.AccelerationY; //Ay axis[2] = state.AccelerationZ; //Az axis[3] = state.AngularAccelerationX; //aAx axis[4] = state.AngularAccelerationY; //aAy axis[5] = state.AngularAccelerationZ; //aAz axis[6] = state.AngularVelocityX; //aVx axis[7] = state.AngularVelocityY; //aVy axis[8] = state.AngularVelocityZ; //aVz axis[9] = state.ForceX; //Fx axis[10] = state.ForceY; //Fy axis[11] = state.ForceZ; //Fz axis[12] = state.RotationX; //Rx axis[13] = state.RotationY; //Ry axis[14] = state.RotationZ; //Rz axis[15] = state.TorqueX; //Tx axis[16] = state.TorqueY; //Ty axis[17] = state.TorqueZ; //Tz axis[18] = state.VelocityX; //Vx axis[19] = state.VelocityY; //Vy axis[20] = state.VelocityZ; //Vz axis[21] = state.X; //x axis[22] = state.Y; //y axis[23] = state.Z; //z int asl = state.GetAccelerationSliders().Length; int fsl = state.GetForceSliders().Length; int vsl = state.GetVelocitySliders().Length; int sl = state.GetSliders().Length; Array.Copy(state.GetAccelerationSliders(), 0, axis, 24, asl); Array.Copy(state.GetForceSliders(), 0, axis, 24 + asl, fsl); Array.Copy(state.GetVelocitySliders(), 0, axis, 24 + asl + fsl, vsl); Array.Copy(state.GetForceSliders(), 0, axis, 24 + asl + fsl + vsl, sl); //Save previous Array.Copy(button, buttonPrev, button.Length); //Update button values //first, convert powController into boolean array to represent them as buttons int[] pov = state.GetPointOfViewControllers(); int povl = pov.Length; bool[] povButton = new bool[povl * 4]; for (int i = 0; i < povl; i += 4) { int povValue = pov[i / 4]; if (povValue == -1) { povButton[i + 0] = false; povButton[i + 1] = false; povButton[i + 2] = false; povButton[i + 3] = false; continue; } //north if (povValue >= 31500 || povValue <= 4500) { povButton[i + 0] = true; } //east if (povValue >= 4500 && povValue <= 13500) { povButton[i + 1] = true; } //south if (povValue >= 13500 && povValue <= 22500) { povButton[i + 2] = true; } //west if (povValue >= 22500 && povValue <= 31500) { povButton[i + 3] = true; } } int bl = state.GetButtons().Length; Array.Copy(state.GetButtons(), 0, button, 0, bl); Array.Copy(povButton, 0, button, bl, povButton.Length); //TEMP for debugging of joystick input /* * if (povPrev == null) * { * aslidersPrev = state.GetAccelerationSliders(); * fslidersPrev = state.GetForceSliders(); * povPrev = state.GetPointOfViewControllers(); * slidersPrev = state.GetSliders(); * vslidersPrev = state.GetVelocitySliders(); * } * * int[] asliders = state.GetAccelerationSliders(); * int[] fsliders = state.GetForceSliders(); * int[] povC = state.GetPointOfViewControllers(); * int[] sliders = state.GetSliders(); * int[] vsliders = state.GetVelocitySliders(); * * for(int i = 0; i < asliders.Length; i++) * { * if (asliders[i] != aslidersPrev[i]) * Console.WriteLine(asliders[i]); * } * aslidersPrev = asliders; * * for (int i = 0; i < fsliders.Length; i++) * { * if (fsliders[i] != fslidersPrev[i]) * Console.WriteLine(fsliders[i]); * } * fslidersPrev = fsliders; * * for (int i = 0; i < pov.Length; i++) * { * if (povC[i] != povPrev[i]) * Console.WriteLine(povC[i]); * } * povPrev = povC; * * for (int i = 0; i < sliders.Length; i++) * { * if (sliders[i] != slidersPrev[i]) * Console.WriteLine(sliders[i]); * } * slidersPrev = sliders; * * for (int i = 0; i < vsliders.Length; i++) * { * if (vsliders[i] != vslidersPrev[i]) * Console.WriteLine(vsliders[i]); * } * vslidersPrev = vsliders; */ }
public void tポーリング(bool bWindowがアクティブ中, bool bバッファ入力有効) { #region [ bButtonフラグ初期化 ] for (int i = 0; i < 256; i++) { this.bButtonPushDown[i] = false; this.bButtonPullUp[i] = false; } #endregion if (bWindowがアクティブ中) { this.list入力イベント.Clear(); // #xxxxx 2012.6.11 yyagi; To optimize, I removed new(); #region [ 入力 ] //----------------------------- JoystickState ButtonState = Joystick.GetState(ID); if (ButtonState.IsConnected) { #region [ X軸- ] //----------------------------- if (ButtonState.GetAxis(0) < -0.5) { if (this.bButtonState[0] == false) { STInputEvent ev = new STInputEvent() { nKey = 0, b押された = true, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[0] = true; this.bButtonPushDown[0] = true; } } else { if (this.bButtonState[0] == true) { STInputEvent ev = new STInputEvent() { nKey = 0, b押された = false, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[0] = false; this.bButtonPullUp[0] = true; } } //----------------------------- #endregion #region [ X軸+ ] //----------------------------- if (ButtonState.GetAxis(0) > 0.5) { if (this.bButtonState[1] == false) { STInputEvent ev = new STInputEvent() { nKey = 1, b押された = true, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[1] = true; this.bButtonPushDown[1] = true; } } else { if (this.bButtonState[1] == true) { STInputEvent event7 = new STInputEvent() { nKey = 1, b押された = false, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(event7); this.bButtonState[1] = false; this.bButtonPullUp[1] = true; } } //----------------------------- #endregion #region [ Y軸- ] //----------------------------- if (ButtonState.GetAxis(1) < -0.5) { if (this.bButtonState[2] == false) { STInputEvent ev = new STInputEvent() { nKey = 2, b押された = true, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[2] = true; this.bButtonPushDown[2] = true; } } else { if (this.bButtonState[2] == true) { STInputEvent ev = new STInputEvent() { nKey = 2, b押された = false, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[2] = false; this.bButtonPullUp[2] = true; } } //----------------------------- #endregion #region [ Y軸+ ] //----------------------------- if (ButtonState.GetAxis(1) > 0.5) { if (this.bButtonState[3] == false) { STInputEvent ev = new STInputEvent() { nKey = 3, b押された = true, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[3] = true; this.bButtonPushDown[3] = true; } } else { if (this.bButtonState[3] == true) { STInputEvent ev = new STInputEvent() { nKey = 3, b押された = false, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[3] = false; this.bButtonPullUp[3] = true; } } //----------------------------- #endregion #region [ Z軸- ] //----------------------------- if (ButtonState.GetAxis(2) < -0.5) { if (this.bButtonState[4] == false) { STInputEvent ev = new STInputEvent() { nKey = 4, b押された = true, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[4] = true; this.bButtonPushDown[4] = true; } } else { if (this.bButtonState[4] == true) { STInputEvent ev = new STInputEvent() { nKey = 4, b押された = false, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[4] = false; this.bButtonPullUp[4] = true; } } //----------------------------- #endregion #region [ Z軸+ ] //----------------------------- if (ButtonState.GetAxis(2) > 0.5) { if (this.bButtonState[5] == false) { STInputEvent ev = new STInputEvent() { nKey = 5, b押された = true, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[5] = true; this.bButtonPushDown[5] = true; } } else { if (this.bButtonState[5] == true) { STInputEvent event15 = new STInputEvent() { nKey = 5, b押された = false, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(event15); this.bButtonState[5] = false; this.bButtonPullUp[5] = true; } } //----------------------------- #endregion #region [ Z軸回転- ] //----------------------------- if (ButtonState.GetAxis(3) < -0.5) { if (this.bButtonState[6] == false) { STInputEvent ev = new STInputEvent() { nKey = 6, b押された = true, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[6] = true; this.bButtonPushDown[6] = true; } } else { if (this.bButtonState[4] == true) { STInputEvent ev = new STInputEvent() { nKey = 6, b押された = false, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[6] = false; this.bButtonPullUp[6] = true; } } //----------------------------- #endregion #region [ Z軸回転+ ] //----------------------------- if (ButtonState.GetAxis(3) > 0.5) { if (this.bButtonState[7] == false) { STInputEvent ev = new STInputEvent() { nKey = 7, b押された = true, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bButtonState[7] = true; this.bButtonPushDown[7] = true; } } else { if (this.bButtonState[7] == true) { STInputEvent event15 = new STInputEvent() { nKey = 7, b押された = false, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(event15); this.bButtonState[7] = false; this.bButtonPullUp[7] = true; } } //----------------------------- #endregion #region [ Button ] //----------------------------- bool bIsButtonPressedReleased = false; for (int j = 0; j < 128; j++) { if (this.bButtonState[8 + j] == false && ButtonState.IsButtonDown(j)) { STInputEvent item = new STInputEvent() { nKey = 8 + j, b押された = true, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(item); this.bButtonState[8 + j] = true; this.bButtonPushDown[8 + j] = true; bIsButtonPressedReleased = true; } else if (this.bButtonState[8 + j] == true && !ButtonState.IsButtonDown(j)) { STInputEvent item = new STInputEvent() { nKey = 8 + j, b押された = false, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(item); this.bButtonState[8 + j] = false; this.bButtonPullUp[8 + j] = true; bIsButtonPressedReleased = true; } } //----------------------------- #endregion // #24341 2011.3.12 yyagi: POV support #region [ POV HAT 4/8way (only single POV switch is supported)] JoystickHatState hatState = ButtonState.GetHat(JoystickHat.Hat0); for (int nWay = 0; nWay < 8; nWay++) { if (hatState.Position == (OpenTK.Input.HatPosition)nWay + 1) { if (this.bButtonState[8 + 128 + nWay] == false) { STInputEvent stevent = new STInputEvent() { nKey = 8 + 128 + nWay, b押された = true, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(stevent); this.bButtonState[stevent.nKey] = true; this.bButtonPushDown[stevent.nKey] = true; } bIsButtonPressedReleased = true; } } if (bIsButtonPressedReleased == false) // #xxxxx 2011.12.3 yyagi 他のボタンが何も押され/離されてない=POVが離された { int nWay = 0; for (int i = 8 + 0x80; i < 8 + 0x80 + 8; i++) { // 離されたボタンを調べるために、元々押されていたボタンを探す。 if (this.bButtonState[i] == true) // DirectInputを直接いじるならこんなことしなくて良いのに、あぁ面倒。 { // この処理が必要なために、POVを1個しかサポートできない。無念。 nWay = i; break; } } if (nWay != 0) { STInputEvent stevent = new STInputEvent() { nKey = nWay, b押された = false, nTimeStamp = CSoundManager.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(stevent); this.bButtonState[nWay] = false; this.bButtonPullUp[nWay] = true; } } #endregion //----------------------------- #endregion } } }
private string GetStateAsText(JoystickState state) { string strText = string.Empty; string joyState = string.Format("Axis : {0:+0000;-0000} / {1:+0000;-0000} / {2:+0000;-0000}\n", state.X, state.Y, state.Z); joyState += string.Format("Rotation: {0:+0000;-0000} / {1:+0000;-0000} / {2:+0000;-0000}\n\n", state.Rx, state.Ry, state.Rz); int[] slider = state.GetSlider(); joyState += string.Format("Slider : 0: {0:+0000;-0000} 1: {1:+0000;-0000}\n\n", slider[0], slider[1]); int[] pov = state.GetPointOfView(); switch (pov[0]) { case 0: { joyState += string.Format("POV : North\n"); break; } case 4500: { joyState += string.Format("POV : NorthEast\n"); break; } case 9000: { joyState += string.Format("POV : East\n"); break; } case 13500: { joyState += string.Format("POV : SouthEast\n"); break; } case 18000: { joyState += string.Format("POV : South\n"); break; } case 22500: { joyState += string.Format("POV : SouthWest\n"); break; } case 27000: { joyState += string.Format("POV : West\n"); break; } case 31500: { joyState += string.Format("POV : NorthWest\n"); break; } default: { break; } } // Fill up text with which buttons are pressed byte[] buttons = state.GetButtons(); int button = 0; foreach (byte b in buttons) { if (0 != (b & 0x80)) { strText += button.ToString("00 "); } button++; } if (strText != string.Empty) { joyState += "Buttons : " + strText; } return(joyState); }
public double GetValue(JoystickState joystickState, int povIndex) { // Position is degrees from North. return(joystickState.GetPointOfViewControllers()[povIndex] / 100d); }
public JoystickState(JoystickState state) { this.direction = state.direction; this.state = state.state; }
void StickEvent(JoystickState state) { if (state.UsbID != USB_ID && state.UsbID != USB_ID_COMBINED) { return; } foreach (KeyValuePair <string, int> entry in state.Data) { switch (entry.Key) { case "Connected": if (state.UsbID == USB_ID && Model.activeInHierarchy) { Model.SetActive(entry.Value == 1); } break; case "RotationZ": // Left Throttle // Rotate Z between -30 and 30 Model.SetActive(true); GimbalLeft.transform.eulerAngles = new Vector3(ConvertRange(entry.Value, 0, 65535, 40, -25), GimbalLeft.transform.eulerAngles.y, GimbalLeft.transform.eulerAngles.z); break; case "Z": // Right Throttle // Rotate X between -30 and 30 Model.SetActive(true); GimbalRight.transform.eulerAngles = new Vector3(ConvertRange(entry.Value, 0, 65535, 40, -25), GimbalRight.transform.eulerAngles.y, GimbalRight.transform.eulerAngles.z); break; case "Buttons28": // Right Throttle Idle/Off if (entry.Value == 0) { GimbalRight.transform.eulerAngles = new Vector3(-25, GimbalRight.transform.eulerAngles.y, GimbalRight.transform.eulerAngles.z); } else { GimbalRight.transform.eulerAngles = new Vector3(-35, GimbalRight.transform.eulerAngles.y, GimbalRight.transform.eulerAngles.z); } break; case "Buttons29": // Left Throttle Idle/Off if (entry.Value == 0) { GimbalLeft.transform.eulerAngles = new Vector3(-25, GimbalLeft.transform.eulerAngles.y, GimbalLeft.transform.eulerAngles.z); } else { GimbalLeft.transform.eulerAngles = new Vector3(-35, GimbalLeft.transform.eulerAngles.y, GimbalLeft.transform.eulerAngles.z); } break; case "Sliders0": // Friction GimbalFriction.transform.eulerAngles = new Vector3(ConvertRange(entry.Value, 0, 65535, 40, -40), GimbalFriction.transform.eulerAngles.y, GimbalFriction.transform.eulerAngles.z); break; case "Buttons5": MicSwitch.transform.localEulerAngles = Vector3.up * ((entry.Value == 0) ? 0.0f : 10.0f); break; case "Buttons3": MicSwitch.transform.localEulerAngles = Vector3.down * ((entry.Value == 0) ? 0.0f : 10.0f); break; case "Buttons2": MicSwitch.transform.localEulerAngles = Vector3.forward * ((entry.Value == 0) ? 0.0f : 10.0f); break; case "Buttons4": MicSwitch.transform.localEulerAngles = Vector3.back * ((entry.Value == 0) ? 0.0f : 10.0f); break; case "Buttons6": SpeedBrake.transform.localPosition = Vector3.forward * ((entry.Value == 0) ? 0.0f : 0.4f); break; case "Buttons7": SpeedBrake.transform.localPosition = Vector3.back * ((entry.Value == 0) ? 0.0f : 0.4f); break; case "Buttons8": BoatSwitch.transform.localEulerAngles = Vector3.down * ((entry.Value == 0) ? 0.0f : FLIP_SWITCH_ROTATION); break; case "Buttons9": BoatSwitch.transform.localEulerAngles = Vector3.up * ((entry.Value == 0) ? 0.0f : FLIP_SWITCH_ROTATION); break; case "Buttons10": ChinaHat.transform.localEulerAngles = Vector3.down * ((entry.Value == 0) ? 0.0f : FLIP_SWITCH_ROTATION); break; case "Buttons11": ChinaHat.transform.localEulerAngles = Vector3.up * ((entry.Value == 0) ? 0.0f : FLIP_SWITCH_ROTATION); break; case "PointOfViewControllers0": switch (entry.Value) { case -1: // zero CoolieHat.transform.localEulerAngles = Vector3.zero; break; case 0: // up CoolieHat.transform.localEulerAngles = Vector3.left * 10.0f; break; case 4500: // up/right CoolieHat.transform.localEulerAngles = Vector3.left * 10.0f + Vector3.up * 10.0f; break; case 9000: // right CoolieHat.transform.localEulerAngles = Vector3.up * 10.0f; break; case 13500: // down/right CoolieHat.transform.localEulerAngles = Vector3.up * 10.0f + Vector3.right * 10.0f; break; case 18000: // down CoolieHat.transform.localEulerAngles = Vector3.right * 10.0f; break; case 22500: // down/left CoolieHat.transform.localEulerAngles = Vector3.right * 10.0f + Vector3.down * 10.0f; break; case 27000: // left CoolieHat.transform.localEulerAngles = Vector3.down * 10.0f; break; case 31500: // up/left CoolieHat.transform.localEulerAngles = Vector3.down * 10.0f + Vector3.left * 10.0f; break; } break; case "Buttons14": LeftThrottleButton.transform.localPosition = Vector3.back * ((entry.Value == 0) ? 0.0f : 0.003f); break; case "Buttons15": FlowL.transform.eulerAngles = Vector3.right * ((entry.Value == 0) ? 0.0f : 40.0f); break; case "Buttons16": FlowR.transform.eulerAngles = Vector3.right * ((entry.Value == 0) ? 0.0f : 40.0f); break; case "Buttons17": IgnL.transform.eulerAngles = Vector3.right * ((entry.Value == 0) ? 0.0f : -FLIP_SWITCH_ROTATION); break; case "Buttons30": IgnL.transform.eulerAngles = Vector3.right * ((entry.Value == 0) ? 0.0f : FLIP_SWITCH_ROTATION); break; case "Buttons18": IgnR.transform.eulerAngles = Vector3.right * ((entry.Value == 0) ? 0.0f : -FLIP_SWITCH_ROTATION); break; case "Buttons31": IgnR.transform.eulerAngles = Vector3.right * ((entry.Value == 0) ? 0.0f : FLIP_SWITCH_ROTATION); break; case "Buttons19": APU.transform.eulerAngles = Vector3.right * ((entry.Value == 0) ? 0.0f : 40.0f); break; case "Buttons20": LG.transform.localPosition = Vector3.down * ((entry.Value == 0) ? 0.0f : 0.0035f); break; case "Buttons25": AutopilotEngage.transform.localPosition = Vector3.down * ((entry.Value == 0) ? 0.0f : 0.0035f); break; case "Buttons23": EAC.transform.eulerAngles = Vector3.right * ((entry.Value == 0) ? 0.0f : 40.0f); break; case "Buttons24": RDR.transform.eulerAngles = Vector3.right * ((entry.Value == 0) ? 0.0f : 40.0f); break; case "Buttons26": AutopilotLaste.transform.eulerAngles = Vector3.right * ((entry.Value == 0) ? 0.0f : FLIP_SWITCH_ROTATION); break; case "Buttons27": AutopilotLaste.transform.eulerAngles = Vector3.right * ((entry.Value == 0) ? 0.0f : -FLIP_SWITCH_ROTATION); break; case "Buttons21": Flaps.transform.eulerAngles = Vector3.right * ((entry.Value == 0) ? 0.0f : FLIP_SWITCH_ROTATION); break; case "Buttons22": Flaps.transform.eulerAngles = Vector3.right * ((entry.Value == 0) ? 0.0f : -FLIP_SWITCH_ROTATION); break; case "Buttons12": PinkySwitch.transform.localEulerAngles = Vector3.up * ((entry.Value == 0) ? 0.0f : FLIP_SWITCH_ROTATION); break; case "Buttons13": PinkySwitch.transform.localEulerAngles = Vector3.up * ((entry.Value == 0) ? 0.0f : -FLIP_SWITCH_ROTATION); break; } } }
private static extern UInt32 _GetPosition(UInt32 rID, ref JoystickState pPosition);
public MyJoystickState(JoystickState state) { baseJoystickState = state; }
// ---------------------- override protected void OnUpdateAnimator(bool skipAnim) { #if UNITY_EDITOR if (!UnityEditor.EditorApplication.isPlaying) { //this.CheckHierarchy(); //return; } #endif TouchJoystick joystick = (TouchJoystick)this.sourceControl; if ((joystick == null) || (this.image == null)) { return; } JoystickState joyState = joystick.GetState(); //false); //this.useVirtualJoystickState); SpriteConfig sprite = null; if ((this.spriteMode == SpriteMode.FourWay) || (this.spriteMode == SpriteMode.EightWay)) { Dir curDir = Dir.N; if (this.spriteMode == SpriteMode.FourWay) { curDir = joyState.GetDir4(); } else if (this.spriteMode == SpriteMode.EightWay) { curDir = joyState.GetDir4(); } switch (curDir) { case Dir.U: sprite = this.spriteUp; break; case Dir.UR: sprite = this.spriteUpRight; break; case Dir.R: sprite = this.spriteRight; break; case Dir.DR: sprite = this.spriteDownRight; break; case Dir.D: sprite = this.spriteDown; break; case Dir.DL: sprite = this.spriteDownLeft; break; case Dir.L: sprite = this.spriteLeft; break; case Dir.UL: sprite = this.spriteUpLeft; break; } } if (joystick.Pressed() && ((sprite == null) || !sprite.enabled)) { sprite = this.spriteNeutralPressed; } if (((sprite == null) || !sprite.enabled)) { sprite = this.spriteNeutral; } if (!CFUtils.editorStopped && !this.IsIllegallyAttachedToSource()) { Vector2 joyVec = joyState.GetVectorEx((joystick.shape == TouchControl.Shape.Rectangle) || (joystick.shape == TouchControl.Shape.Square)); if (this.animateTransl) { this.extraOffset = CFUtils.SmoothTowardsVec2(this.extraOffset, Vector2.Scale(joyVec, this.moveScale), this.translationSmoothingTime, CFUtils.realDeltaTimeClamped, 0.0001f); } else { this.extraOffset = Vector2.zero; } if (this.rotationMode != RotationMode.Disabled) { float targetAngle = 0; if (joystick.Pressed()) { Vector2 v = joyState.GetVector(); if (this.rotationMode == RotationMode.Compass) { if (v.sqrMagnitude > 0.0001f) { this.lastSafeCompassAngle = joyState.GetAngle(); //CFUtils.VecToAngle(v.normalized); } targetAngle = -this.lastSafeCompassAngle; //targetRotation = Quaternion.Euler(0, 0, -this.lastSafeCompassAngle); } else { targetAngle = ((this.rotationMode == RotationMode.SimpleHorizontal) ? v.x : v.y) * -this.simpleRotationRange; } } else { this.lastSafeCompassAngle = 0; targetAngle = 0; } this.extraRotation = CFUtils.SmoothTowardsAngle(this.extraRotation, targetAngle, this.rotationSmoothingTime, CFUtils.realDeltaTimeClamped, 0.0001f); } } this.BeginSpriteAnim(sprite, skipAnim); this.UpdateSpriteAnimation(skipAnim); }
void UpdateDiStates(DirectInput manager, UserGame game, DeviceDetector detector) { // Get all mapped user devices. var userDevices = SettingsManager.GetMappedDevices(game?.FileName); // Acquire copy of feedbacks for processing. var feedbacks = CopyAndClearFeedbacks(); for (int i = 0; i < userDevices.Count(); i++) { // Update direct input form and return actions (pressed Buttons/DPads, turned Axis/Sliders). var ud = userDevices[i]; JoystickState state = null; JoystickUpdate[] update = null; // Allow if not testing or testing with option enabled. var o = SettingsManager.Options; var allow = !o.TestEnabled || o.TestGetDInputStates; // Note: manager.IsDeviceAttached() use a lot of CPU resources. var isAttached = ud != null && ud.IsOnline; // && manager.IsDeviceAttached(ud.InstanceGuid); if (isAttached && allow) { var device = ud.Device; if (device != null) { var exceptionData = new System.Text.StringBuilder(); try { if (o.UseDeviceBufferedData && device.Properties.BufferSize == 0) { // Set BufferSize in order to use buffered data. device.Properties.BufferSize = 128; } var isVirtual = ((EmulationType)game.EmulationType).HasFlag(EmulationType.Virtual); var hasForceFeedback = device.Capabilities.Flags.HasFlag(DeviceFlags.ForceFeedback); // Exclusive mode required only if force feedback is available and device is virtual there are no info about effects. var exclusiveRequired = hasForceFeedback && (isVirtual || ud.DeviceEffects == null); // If exclusive mode is required and mode is unknown or not exclusive then... if (exclusiveRequired && (!ud.IsExclusiveMode.HasValue || !ud.IsExclusiveMode.Value)) { var flags = CooperativeLevel.Background | CooperativeLevel.Exclusive; // Reacquire device in exclusive mode. exceptionData.AppendLine("Unacquire (Exclusive)..."); device.Unacquire(); exceptionData.AppendLine("SetCooperativeLevel (Exclusive)..."); device.SetCooperativeLevel(detector.DetectorForm.Handle, flags); exceptionData.AppendLine("Acquire (Exclusive)..."); device.Acquire(); ud.IsExclusiveMode = true; } // If current mode must be non exclusive and mode is unknown or exclusive then... else if (!exclusiveRequired && (!ud.IsExclusiveMode.HasValue || ud.IsExclusiveMode.Value)) { var flags = CooperativeLevel.Background | CooperativeLevel.NonExclusive; // Reacquire device in non exclusive mode so that xinput.dll can control force feedback. exceptionData.AppendLine("Unacquire (NonExclusive)..."); device.Unacquire(); exceptionData.AppendLine("SetCooperativeLevel (Exclusive)..."); device.SetCooperativeLevel(detector.DetectorForm.Handle, flags); exceptionData.AppendLine("Acquire (Acquire)..."); device.Acquire(); ud.IsExclusiveMode = false; } exceptionData.AppendFormat("device.GetCurrentState() // ud.IsExclusiveMode = {0}", ud.IsExclusiveMode).AppendLine(); // Polling - Retrieves data from polled objects on a DirectInput device. // Some devices require pooling (For example original "Xbox Controller S" with XBCD drivers). // If the device does not require polling, calling this method has no effect. // If a device that requires polling is not polled periodically, no new data is received from the device. // Calling this method causes DirectInput to update the device state, generate input // events (if buffered data is enabled), and set notification events (if notification is enabled). device.Poll(); if (o.UseDeviceBufferedData) { // Get buffered data. update = device.GetBufferedData(); } // Get device state. state = device.GetCurrentState(); // Fill device objects. if (ud.DeviceObjects == null) { exceptionData.AppendFormat("AppHelper.GetDeviceObjects(device) // ud.IsExclusiveMode = {0}", ud.IsExclusiveMode).AppendLine(); var dos = AppHelper.GetDeviceObjects(device); ud.DeviceObjects = dos; // Update masks. int axisMask = 0; int actuatorMask = 0; int actuatorCount = 0; if (ud.CapType == (int)SharpDX.DirectInput.DeviceType.Mouse) { CustomDiState.GetMouseAxisMask(dos, device, out axisMask); } else { CustomDiState.GetJoystickAxisMask(dos, device, out axisMask, out actuatorMask, out actuatorCount); } ud.DiAxeMask = axisMask; // Contains information about which axis have force feedback actuator attached. ud.DiActuatorMask = actuatorMask; ud.DiActuatorCount = actuatorCount; CustomDiState.GetJoystickSlidersMask(dos, device); } if (ud.DeviceEffects == null) { exceptionData.AppendFormat("AppHelper.GetDeviceEffects(device) // ud.IsExclusiveMode = {0}", ud.IsExclusiveMode).AppendLine(); ud.DeviceEffects = AppHelper.GetDeviceEffects(device); } // If device support force feedback then... if (hasForceFeedback) { // Get setting related to user device. var setting = SettingsManager.UserSettings.ItemsToArraySyncronized() .FirstOrDefault(x => x.InstanceGuid == ud.InstanceGuid); // If device is mapped to controller then... if (setting != null && setting.MapTo > (int)MapTo.None) { // Get pad setting attached to device. var ps = SettingsManager.GetPadSetting(setting.PadSettingChecksum); if (ps != null) { // If force is enabled then... if (ps.ForceEnable == "1") { if (ud.FFState == null) { ud.FFState = new Engine.ForceFeedbackState(); } // If force update supplied then... var force = feedbacks[(int)setting.MapTo - 1]; if (force != null || ud.FFState.Changed(ps)) { var v = new Vibration(); if (force == null) { v.LeftMotorSpeed = short.MinValue; v.RightMotorSpeed = short.MinValue; } else { v.LeftMotorSpeed = (short)ConvertHelper.ConvertRange(byte.MinValue, byte.MaxValue, short.MinValue, short.MaxValue, force.LargeMotor); v.RightMotorSpeed = (short)ConvertHelper.ConvertRange(byte.MinValue, byte.MaxValue, short.MinValue, short.MaxValue, force.SmallMotor); } // For the future: Investigate device states if force feedback is not working. // var st = ud.Device.GetForceFeedbackState(); //st == SharpDX.DirectInput.ForceFeedbackState // ud.Device.SendForceFeedbackCommand(ForceFeedbackCommand.SetActuatorsOn); exceptionData.AppendFormat("ud.FFState.SetDeviceForces(device) // ud.IsExclusiveMode = {0}", ud.IsExclusiveMode).AppendLine(); ud.FFState.SetDeviceForces(ud, device, ps, v); } } // If force state was created then... else if (ud.FFState != null) { // Stop device forces. exceptionData.AppendFormat("ud.FFState.StopDeviceForces(device) // ud.IsExclusiveMode = {0}", ud.IsExclusiveMode).AppendLine(); ud.FFState.StopDeviceForces(device); ud.FFState = null; } } } } } catch (Exception ex) { var dex = ex as SharpDXException; if (dex != null && dex.ResultCode == SharpDX.DirectInput.ResultCode.InputLost) { // Ignore error. } else if (dex != null && dex.ResultCode == SharpDX.DirectInput.ResultCode.NotAcquired) { // Ignore error } else if (dex != null && dex.ResultCode == SharpDX.DirectInput.ResultCode.Unplugged) { // Ignore error } else { var cx = new DInputException("UpdateDiStates Exception", ex); cx.Data.Add("FFInfo", exceptionData.ToString()); JocysCom.ClassLibrary.Runtime.LogHelper.Current.WriteException(cx); } ud.IsExclusiveMode = null; } } // If this is test device then... else if (TestDeviceHelper.ProductGuid.Equals(ud.ProductGuid)) { // Fill device objects. if (ud.DeviceObjects == null) { var dos = TestDeviceHelper.GetDeviceObjects(); ud.DeviceObjects = dos; // Update masks. ud.DiAxeMask = 0x1 | 0x2 | 0x4 | 0x8; ud.DiSliderMask = 0; } if (ud.DeviceEffects == null) { ud.DeviceEffects = new DeviceEffectItem[0]; } state = TestDeviceHelper.GetCurrentState(ud); } } ud.JoState = state; ud.JoUpdate = update; if (update != null) { if (update.Length > 0) { } } // Update only if state available. if (state != null) { var newState = new CustomDiState(ud.JoState); var newTime = watch.ElapsedTicks; // Remember old state. ud.OldDiState = ud.DiState; ud.OldDiStateTime = ud.DiStateTime; // Update state. ud.DiState = newState; ud.DiStateTime = newTime; // Mouse needs special update. if (ud.Device != null && ud.Device.Information.Type == SharpDX.DirectInput.DeviceType.Mouse) { // If original state is missing then... if (ud.OrgDiState == null) { // Store current values. ud.OrgDiState = newState; ud.OrgDiStateTime = newTime; // Make sure new states have zero values. for (int a = 0; a < newState.Axis.Length; a++) { newState.Axis[a] = -short.MinValue; } for (int s = 0; s < newState.Sliders.Length; s++) { newState.Sliders[s] = -short.MinValue; } } var mouseState = new CustomDiState(new JoystickState()); // Clone button values. Array.Copy(newState.Buttons, mouseState.Buttons, mouseState.Buttons.Length); // //-------------------------------------------------------- // // Map mouse acceleration to axis position. Good for FPS control. // //-------------------------------------------------------- // // This parts needs to be worked on. // //var ticks = (int)(newTime - ud.DiStateTime); // // Update axis with delta. // //for (int a = 0; a < newState.Axis.Length; a++) // // mouseState.Axis[a] = ticks * (newState.Axis[a] - ud.OldDiState.Axis[a]) - short.MinValue; // // Update sliders with delta. // //for (int s = 0; s < newState.Sliders.Length; s++) // // mouseState.Sliders[s] = ticks * (newState.Sliders[s] - ud.OldDiState.Sliders[s]) - short.MinValue; //-------------------------------------------------------- // Map mouse position to axis position. Good for car wheel controls. //-------------------------------------------------------- Calc(ud.OrgDiState.Axis, newState.Axis, mouseState.Axis); Calc(ud.OrgDiState.Sliders, newState.Sliders, mouseState.Sliders); ud.DiState = mouseState; } } } }
public UInt32 GetPosition(UInt32 rID, ref JoystickState pPosition) { return(_GetPosition(rID, ref pPosition)); }
public static JoystickState GetCurrentState(UserDevice ud) { if (watch == null) { watch = new Stopwatch(); watch.Start(); } var elapsed = watch.Elapsed; // Restart timer if out of limits. if (elapsed.TotalMilliseconds > int.MaxValue) { watch.Restart(); elapsed = watch.Elapsed; } // Acquire values. var ts = (int)elapsed.TotalSeconds; var tm = (int)elapsed.TotalMilliseconds; var state = new JoystickState(); // Set Buttons. for (int i = 0; i < ud.CapButtonCount; i++) { var currentLocation = ts % ud.CapButtonCount; // Enable button during its index. state.Buttons[i] = currentLocation == i; } // Do action for 4 seconds [0-3999] ms. var busy = 4000; var half = busy / 2; // then stay for 2 seconds idle [4000-5999] ms. var idle = 2000; // 6 = 4 + 2. var time = tm % (busy + idle); var invert = tm % ((busy + idle) * 2) > (busy + idle); // Set POVs. for (int i = 0; i < ud.CapPovCount; i++) { // Rotate POVs 360 degrees in 4 seconds forward and back. var degree = -1; if (time < busy) { // Shift busy value by half so movement starts from the centre. var value = (time + busy / 2) % busy; if (time <= half) { // Convert [ 0-1999] to [0-35999]. degree = ConvertHelper.ConvertRange(0, half - 1, 0, 35999, value); } else { // Convert [2000-3999] to [35999-0]. degree = ConvertHelper.ConvertRange(half, busy - 1, 35999, 0, value); } } state.PointOfViewControllers[i] = degree; } // Set Axis. var axis = CustomDiState.GetAxisFromState(state); // Get information about axis. var axisObjects = ud.DeviceObjects .Where(x => x.Flags.HasFlag(DeviceObjectTypeFlags.AbsoluteAxis) || x.Flags.HasFlag(DeviceObjectTypeFlags.RelativeAxis)).ToArray(); for (int i = 0; i < axisObjects.Count(); i++) { var ao = axisObjects[i]; // If axis index is even. var isEven = i % 2 == 0; var position = isEven // Default position is in the center. ? ushort.MaxValue - short.MaxValue // Default position is at the bottom. : 0; // Move axis in 4 seconds, then stay for 2 seconds idle. if (time < busy) { if (isEven) { // Convert [0-3999] to [0-2Pi]. var angle = time * 2 * Math.PI / busy; var sine = Math.Sin(angle); if (invert && isEven) { sine *= -1f; } var range = ConvertHelper.ConvertToShort((float)sine); position = ConvertHelper.ConvertRange(short.MinValue, short.MaxValue, ushort.MinValue, ushort.MaxValue, range); } else { position = time < half // Move up [0-1999]. ? ConvertHelper.ConvertRange(0, half - 1, ushort.MinValue, ushort.MaxValue, time) // Move down [2000-3999]. : ConvertHelper.ConvertRange(half, busy - 1, ushort.MaxValue, ushort.MinValue, time); } } axis[i] = position; } CustomDiState.SetStateFromAxis(state, axis); // Get sliders array. var sliders = CustomDiState.GetSlidersFromState(state); // Set sliders. for (int i = 0; i < sliders.Length; i++) { var isEven = i % 2 == 0; var position = isEven // Default position is in the center. ? ushort.MaxValue - short.MaxValue // Default position is at the bottom. : 0; // Move slider in 4 seconds, then stay for 2 seconds idle. if (time < busy) { if (isEven) { // Convert [0-3999] to [0-2Pi]. var angle = time * 2 * Math.PI / busy; var sine = Math.Sin(angle); if (invert && isEven) { sine *= -1f; } var range = ConvertHelper.ConvertToShort((float)sine); position = ConvertHelper.ConvertRange(short.MinValue, short.MaxValue, ushort.MinValue, ushort.MaxValue, range); } else { position = time < half // Move up. ? ConvertHelper.ConvertRange(0, half - 1, ushort.MinValue, ushort.MaxValue, time) // Move down. : ConvertHelper.ConvertRange(half, busy - 1, ushort.MaxValue, ushort.MinValue, time); } } sliders[i] = position; } CustomDiState.SetStateFromSliders(state, sliders); // Return state. return(state); }
public ControllerKeys GetButtons() { // NOTE: This should be initialized AFTER GTK for compat reasons with OpenTK SDL2 backend and GTK on Linux. // BODY: Usage of Joystick.GetState must be defer to after GTK full initialization. Otherwise, GTK will segfault because SDL2 was already init *sighs* if (!IsEnabled()) { return(0); } JoystickState joystickState = Joystick.GetState(_config.Index); ControllerKeys buttons = 0; if (IsActivated(joystickState, _config.LeftJoycon.DPadUp)) { buttons |= ControllerKeys.DpadUp; } if (IsActivated(joystickState, _config.LeftJoycon.DPadDown)) { buttons |= ControllerKeys.DpadDown; } if (IsActivated(joystickState, _config.LeftJoycon.DPadLeft)) { buttons |= ControllerKeys.DpadLeft; } if (IsActivated(joystickState, _config.LeftJoycon.DPadRight)) { buttons |= ControllerKeys.DpadRight; } if (IsActivated(joystickState, _config.LeftJoycon.StickButton)) { buttons |= ControllerKeys.LStick; } if (IsActivated(joystickState, _config.LeftJoycon.ButtonMinus)) { buttons |= ControllerKeys.Minus; } if (IsActivated(joystickState, _config.LeftJoycon.ButtonL)) { buttons |= ControllerKeys.L; } if (IsActivated(joystickState, _config.LeftJoycon.ButtonZl)) { buttons |= ControllerKeys.Zl; } if (IsActivated(joystickState, _config.LeftJoycon.ButtonSl)) { buttons |= ControllerKeys.SlLeft; } if (IsActivated(joystickState, _config.LeftJoycon.ButtonSr)) { buttons |= ControllerKeys.SrLeft; } if (IsActivated(joystickState, _config.RightJoycon.ButtonA)) { buttons |= ControllerKeys.A; } if (IsActivated(joystickState, _config.RightJoycon.ButtonB)) { buttons |= ControllerKeys.B; } if (IsActivated(joystickState, _config.RightJoycon.ButtonX)) { buttons |= ControllerKeys.X; } if (IsActivated(joystickState, _config.RightJoycon.ButtonY)) { buttons |= ControllerKeys.Y; } if (IsActivated(joystickState, _config.RightJoycon.StickButton)) { buttons |= ControllerKeys.RStick; } if (IsActivated(joystickState, _config.RightJoycon.ButtonPlus)) { buttons |= ControllerKeys.Plus; } if (IsActivated(joystickState, _config.RightJoycon.ButtonR)) { buttons |= ControllerKeys.R; } if (IsActivated(joystickState, _config.RightJoycon.ButtonZr)) { buttons |= ControllerKeys.Zr; } if (IsActivated(joystickState, _config.RightJoycon.ButtonSl)) { buttons |= ControllerKeys.SlRight; } if (IsActivated(joystickState, _config.RightJoycon.ButtonSr)) { buttons |= ControllerKeys.SrRight; } return(buttons); }
private static bool IsAnyButtonPressed(out ControllerInputId pressedButton, int index, double triggerThreshold) { JoystickState joystickState = Joystick.GetState(index); JoystickCapabilities joystickCapabilities = Joystick.GetCapabilities(index); //Buttons for (int i = 0; i != joystickCapabilities.ButtonCount; i++) { if (joystickState.IsButtonDown(i)) { Enum.TryParse($"Button{i}", out pressedButton); return(true); } } //Axis for (int i = 0; i != joystickCapabilities.AxisCount; i++) { if (joystickState.GetAxis(i) > 0.5f && joystickState.GetAxis(i) > triggerThreshold) { Enum.TryParse($"Axis{i}", out pressedButton); return(true); } } //Hats for (int i = 0; i != joystickCapabilities.HatCount; i++) { JoystickHatState hatState = joystickState.GetHat((JoystickHat)i); string pos = null; if (hatState.IsUp) { pos = "Up"; } if (hatState.IsDown) { pos = "Down"; } if (hatState.IsLeft) { pos = "Left"; } if (hatState.IsRight) { pos = "Right"; } if (pos == null) { continue; } Enum.TryParse($"Hat{i}{pos}", out pressedButton); return(true); } pressedButton = ControllerInputId.Unbound; return(false); }
/// <summary> /// Updates the rcoverride values and controls the mode changes /// </summary> void mainloop() { while (enabled) { try { System.Threading.Thread.Sleep(50); //joystick stuff joystick.Poll(); state = joystick.CurrentJoystickState; int[] slider = state.GetSlider(); if (elevons) { //g.channel_roll.set_pwm(BOOL_TO_SIGN(g.reverse_elevons) * (BOOL_TO_SIGN(g.reverse_ch2_elevon) * int(ch2_temp - elevon2_trim) - BOOL_TO_SIGN(g.reverse_ch1_elevon) * int(ch1_temp - elevon1_trim)) / 2 + 1500); //g.channel_pitch.set_pwm( (BOOL_TO_SIGN(g.reverse_ch2_elevon) * int(ch2_temp - elevon2_trim) + BOOL_TO_SIGN(g.reverse_ch1_elevon) * int(ch1_temp - elevon1_trim)) / 2 + 1500); ushort roll = pickchannel(1, JoyChannels[1].axis, false, JoyChannels[1].expo); ushort pitch = pickchannel(2, JoyChannels[2].axis, false, JoyChannels[2].expo); if (getJoystickAxis(1) != Joystick.joystickaxis.None) { MainV2.comPort.MAV.cs.rcoverridech1 = (ushort)(BOOL_TO_SIGN(JoyChannels[1].reverse) * ((int)(pitch - 1500) - (int)(roll - 1500)) / 2 + 1500); } if (getJoystickAxis(2) != Joystick.joystickaxis.None) { MainV2.comPort.MAV.cs.rcoverridech2 = (ushort)(BOOL_TO_SIGN(JoyChannels[2].reverse) * ((int)(pitch - 1500) + (int)(roll - 1500)) / 2 + 1500); } } else { if (getJoystickAxis(1) != Joystick.joystickaxis.None) { MainV2.comPort.MAV.cs.rcoverridech1 = pickchannel(1, JoyChannels[1].axis, JoyChannels[1].reverse, JoyChannels[1].expo);//(ushort)(((int)state.Rz / 65.535) + 1000); } if (getJoystickAxis(2) != Joystick.joystickaxis.None) { MainV2.comPort.MAV.cs.rcoverridech2 = pickchannel(2, JoyChannels[2].axis, JoyChannels[2].reverse, JoyChannels[2].expo);//(ushort)(((int)state.Y / 65.535) + 1000); } } if (getJoystickAxis(3) != Joystick.joystickaxis.None) { MainV2.comPort.MAV.cs.rcoverridech3 = pickchannel(3, JoyChannels[3].axis, JoyChannels[3].reverse, JoyChannels[3].expo);//(ushort)(1000 - ((int)slider[0] / 65.535) + 1000); } if (getJoystickAxis(4) != Joystick.joystickaxis.None) { MainV2.comPort.MAV.cs.rcoverridech4 = pickchannel(4, JoyChannels[4].axis, JoyChannels[4].reverse, JoyChannels[4].expo);//(ushort)(((int)state.X / 65.535) + 1000); } if (getJoystickAxis(5) != Joystick.joystickaxis.None) { MainV2.comPort.MAV.cs.rcoverridech5 = pickchannel(5, JoyChannels[5].axis, JoyChannels[5].reverse, JoyChannels[5].expo); } if (getJoystickAxis(6) != Joystick.joystickaxis.None) { MainV2.comPort.MAV.cs.rcoverridech6 = pickchannel(6, JoyChannels[6].axis, JoyChannels[6].reverse, JoyChannels[6].expo); } if (getJoystickAxis(7) != Joystick.joystickaxis.None) { MainV2.comPort.MAV.cs.rcoverridech7 = pickchannel(7, JoyChannels[7].axis, JoyChannels[7].reverse, JoyChannels[7].expo); } if (getJoystickAxis(8) != Joystick.joystickaxis.None) { MainV2.comPort.MAV.cs.rcoverridech8 = pickchannel(8, JoyChannels[8].axis, JoyChannels[8].reverse, JoyChannels[8].expo); } foreach (JoyButton but in JoyButtons) { if (but.buttonno != -1 && getButtonState(but.buttonno)) { string mode = but.mode; MainV2.instance.BeginInvoke((System.Windows.Forms.MethodInvoker) delegate() { try { MainV2.comPort.setMode(mode); } catch { CustomMessageBox.Show("Failed to change Modes"); } }); } } //Console.WriteLine("{0} {1} {2} {3}", MainV2.comPort.MAV.cs.rcoverridech1, MainV2.comPort.MAV.cs.rcoverridech2, MainV2.comPort.MAV.cs.rcoverridech3, MainV2.comPort.MAV.cs.rcoverridech4); } catch (Exception ex) { log.Info("Joystick thread error " + ex.ToString()); } // so we cant fall out } }
public InputState GetInputState() { var ret = new InputState(); ret.IsCancel = GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed; TouchCollection touchCollection = TouchPanel.GetState(); foreach (TouchLocation item in touchCollection) { if ((item.State == TouchLocationState.Pressed) || (item.State == TouchLocationState.Moved)) { var pos = new Position() { X = item.Position.X, Y = item.Position.Y }; ret.Positions.Add(pos); } } while (TouchPanel.IsGestureAvailable) { GestureSample gesture = TouchPanel.ReadGesture(); if ((gesture.GestureType == GestureType.HorizontalDrag) && !gestureProcessing) { if (gesture.Delta.X > 0) { lastGesture = JoystickState.Right; gestureProcessing = true; } else if (gesture.Delta.X < 0) { lastGesture = JoystickState.Left; gestureProcessing = true; } } else if ((gesture.GestureType == GestureType.VerticalDrag) && !gestureProcessing) { if (gesture.Delta.Y > 0) { lastGesture = JoystickState.Down; gestureProcessing = true; } else if (gesture.Delta.Y < 0) { lastGesture = JoystickState.Up; gestureProcessing = true; } } else if (gesture.GestureType == GestureType.DragComplete) { gestureProcessing = false; ret.Joystick = lastGesture; } else if (gesture.GestureType == GestureType.Tap) { ret.Joystick = JoystickState.Press; var pos = new Position() { X = gesture.Position.X, Y = gesture.Position.Y }; ret.Positions.Add(pos); } } return(ret); }
public static joystickaxis getMovingAxis(string name, int threshold) { self.name = name; DeviceList joysticklist = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly); bool found = false; Device joystick = null; foreach (DeviceInstance device in joysticklist) { if (device.ProductName == name) { joystick = new Device(device.InstanceGuid); found = true; break; } } if (!found) { return(joystickaxis.ARx); } joystick.SetDataFormat(DeviceDataFormat.Joystick); joystick.Acquire(); CustomMessageBox.Show("Please ensure you have calibrated your joystick in Windows first"); joystick.Poll(); JoystickState obj = joystick.CurrentJoystickState; Hashtable values = new Hashtable(); Type type = obj.GetType(); PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { values[property.Name] = int.Parse(property.GetValue(obj, null).ToString()); } values["Slider1"] = obj.GetSlider()[0]; values["Slider2"] = obj.GetSlider()[1]; CustomMessageBox.Show("Please move the joystick axis you want assigned to this function after clicking ok"); DateTime start = DateTime.Now; while (start.AddSeconds(10) > DateTime.Now) { joystick.Poll(); JoystickState nextstate = joystick.CurrentJoystickState; int[] slider = nextstate.GetSlider(); type = nextstate.GetType(); properties = type.GetProperties(); foreach (PropertyInfo property in properties) { //Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null)); log.InfoFormat("test name {0} old {1} new {2} ", property.Name, values[property.Name], int.Parse(property.GetValue(nextstate, null).ToString())); log.InfoFormat("{0} {1}", (int)values[property.Name], (int.Parse(property.GetValue(nextstate, null).ToString()) + threshold)); if ((int)values[property.Name] > (int.Parse(property.GetValue(nextstate, null).ToString()) + threshold) || (int)values[property.Name] < (int.Parse(property.GetValue(nextstate, null).ToString()) - threshold)) { log.Info(property.Name); joystick.Unacquire(); return((joystickaxis)Enum.Parse(typeof(joystickaxis), property.Name)); } } // slider1 if ((int)values["Slider1"] > (slider[0] + threshold) || (int)values["Slider1"] < (slider[0] - threshold)) { joystick.Unacquire(); return(joystickaxis.Slider1); } // slider2 if ((int)values["Slider2"] > (slider[1] + threshold) || (int)values["Slider2"] < (slider[1] - threshold)) { joystick.Unacquire(); return(joystickaxis.Slider2); } } CustomMessageBox.Show("No valid option was detected"); return(joystickaxis.None); }
private static extern bool _UpdateVJD(UInt32 rID, ref JoystickState pData);
public InputState(MouseState mouse = null, KeyboardState keyboard = null, TouchState touch = null, JoystickState joystick = null, MidiState midi = null) { Mouse = mouse ?? new MouseState(); Keyboard = keyboard ?? new KeyboardState(); Touch = touch ?? new TouchState(); Joystick = joystick ?? new JoystickState(); Midi = midi ?? new MidiState(); }
private static extern bool VJoy_UpdateJoyState(int id, ref JoystickState joyState);