Esempio n. 1
0
 private string GetHatPosition(JoystickHatState hatState)
 {
     if (hatState.IsUp) return "Up";
     if (hatState.IsDown) return "Down";
     if (hatState.IsLeft) return "Left";
     if (hatState.IsRight) return "Right";
     return "";
 }
Esempio n. 2
0
        private bool IsActivated(JoystickState joystickState, ControllerInputId controllerInputId)
        {
            if (controllerInputId <= ControllerInputId.Button20)
            {
                return(joystickState.IsButtonDown((int)controllerInputId));
            }
            else if (controllerInputId <= ControllerInputId.Axis5)
            {
                int axis = controllerInputId - ControllerInputId.Axis0;

                return(joystickState.GetAxis(axis) > TriggerThreshold);
            }
            else if (controllerInputId <= ControllerInputId.Hat2Right)
            {
                int hat = (controllerInputId - ControllerInputId.Hat0Up) / 4;

                int baseHatId = (int)ControllerInputId.Hat0Up + (hat * 4);

                JoystickHatState hatState = joystickState.GetHat((JoystickHat)hat);

                if (hatState.IsUp && ((int)controllerInputId % baseHatId == 0))
                {
                    return(true);
                }
                if (hatState.IsDown && ((int)controllerInputId % baseHatId == 1))
                {
                    return(true);
                }
                if (hatState.IsLeft && ((int)controllerInputId % baseHatId == 2))
                {
                    return(true);
                }
                if (hatState.IsRight && ((int)controllerInputId % baseHatId == 3))
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 3
0
        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);
        }
Esempio n. 4
0
        internal static void ProcessKeyboard()
        {
            if (Interface.CurrentOptions.UseJoysticks)
            {
                for (int k = 0; k < JoystickManager.AttachedJoysticks.Length; k++)
                {
                    JoystickManager.AttachedJoysticks[k].Poll();
                }
            }
            if (Game.CurrentInterface == Game.InterfaceType.Menu && Game.Menu.IsCustomizingControl())
            {
                if (Interface.CurrentOptions.UseJoysticks)
                {
                    for (int k = 0; k < JoystickManager.AttachedJoysticks.Length; k++)
                    {
                        int axes = JoystickManager.AttachedJoysticks[k].AxisCount();
                        for (int i = 0; i < axes; i++)
                        {
                            double aa = JoystickManager.AttachedJoysticks[k].GetAxis(i);
                            if (aa < -0.75)
                            {
                                Game.Menu.SetControlJoyCustomData(k, Interface.JoystickComponent.Axis, i, -1);
                                return;
                            }
                            if (aa > 0.75)
                            {
                                Game.Menu.SetControlJoyCustomData(k, Interface.JoystickComponent.Axis, i, 1);
                                return;
                            }
                        }
                        int buttons = JoystickManager.AttachedJoysticks[k].ButtonCount();
                        for (int i = 0; i < buttons; i++)
                        {
                            if (JoystickManager.AttachedJoysticks[k].GetButton(i) == ButtonState.Pressed)
                            {
                                Game.Menu.SetControlJoyCustomData(k, Interface.JoystickComponent.Button, i, 1);
                                return;
                            }
                        }
                        int hats = JoystickManager.AttachedJoysticks[k].HatCount();
                        for (int i = 0; i < hats; i++)
                        {
                            JoystickHatState hat = JoystickManager.AttachedJoysticks[k].GetHat(i);
                            if (hat.Position != HatPosition.Centered)
                            {
                                Game.Menu.SetControlJoyCustomData(k, Interface.JoystickComponent.Hat, i, (int)hat.Position);
                                return;
                            }
                        }
                    }
                }
                return;
            }
            if (World.MouseGrabEnabled)
            {
                previousMouseState = currentMouseState;
                currentMouseState  = Mouse.GetState();
                if (previousMouseState != currentMouseState)
                {
                    if (World.MouseGrabIgnoreOnce)
                    {
                        World.MouseGrabIgnoreOnce = false;
                    }
                    else if (World.MouseGrabEnabled)
                    {
                        World.MouseGrabTarget = new OpenBveApi.Math.Vector2(currentMouseState.X - previousMouseState.X, currentMouseState.Y - previousMouseState.Y);
                    }
                }
            }

            //Traverse the controls array
            for (int i = 0; i < Interface.CurrentControls.Length; i++)
            {
                int currentDevice = Interface.CurrentControls[i].Device;
                //Check to see if our device is currently available
                switch (Interface.CurrentControls[i].Method)
                {
                case Interface.ControlMethod.Joystick:
                    if (JoystickManager.AttachedJoysticks.Length == 0 || !Joystick.GetCapabilities(Interface.CurrentControls[i].Device).IsConnected)
                    {
                        //Not currently connected
                        continue;
                    }
                    break;

                case Interface.ControlMethod.RailDriver:
                    if (JoystickManager.RailDriverIndex == -1)
                    {
                        //Not currently connected
                        continue;
                    }
                    currentDevice = JoystickManager.RailDriverIndex;
                    break;

                default:
                    //Not a joystick / RD
                    continue;
                }


                switch (Interface.CurrentControls[i].Component)
                {
                case Interface.JoystickComponent.Axis:
                    var axisState = JoystickManager.GetAxis(currentDevice, Interface.CurrentControls[i].Element);
                    if (axisState.ToString(CultureInfo.InvariantCulture) != Interface.CurrentControls[i].LastState)
                    {
                        Interface.CurrentControls[i].LastState = axisState.ToString(CultureInfo.InvariantCulture);
                        if (Interface.CurrentControls[i].InheritedType == Interface.CommandType.AnalogHalf)
                        {
                            if (Math.Sign(axisState) == Math.Sign(Interface.CurrentControls[i].Direction))
                            {
                                axisState = Math.Abs(axisState);
                                if (axisState < Interface.CurrentOptions.JoystickAxisThreshold)
                                {
                                    Interface.CurrentControls[i].AnalogState = 0.0;
                                }
                                else if (Interface.CurrentOptions.JoystickAxisThreshold != 1.0)
                                {
                                    Interface.CurrentControls[i].AnalogState = (axisState - Interface.CurrentOptions.JoystickAxisThreshold) / (1.0 - Interface.CurrentOptions.JoystickAxisThreshold);
                                }
                                else
                                {
                                    Interface.CurrentControls[i].AnalogState = 1.0;
                                }
                            }
                        }
                        else if (Interface.CurrentControls[i].InheritedType == Interface.CommandType.AnalogFull)
                        {
                            axisState *= (float)Interface.CurrentControls[i].Direction;
                            if (axisState > -Interface.CurrentOptions.JoystickAxisThreshold & axisState < Interface.CurrentOptions.JoystickAxisThreshold)
                            {
                                Interface.CurrentControls[i].AnalogState = 0.0;
                            }
                            else if (Interface.CurrentOptions.JoystickAxisThreshold != 1.0)
                            {
                                if (axisState < 0.0)
                                {
                                    Interface.CurrentControls[i].AnalogState = (axisState + Interface.CurrentOptions.JoystickAxisThreshold) / (1.0 - Interface.CurrentOptions.JoystickAxisThreshold);
                                }
                                else if (axisState > 0.0)
                                {
                                    Interface.CurrentControls[i].AnalogState = (axisState - Interface.CurrentOptions.JoystickAxisThreshold) / (1.0 - Interface.CurrentOptions.JoystickAxisThreshold);
                                }
                                else
                                {
                                    Interface.CurrentControls[i].AnalogState = 0.0;
                                }
                            }
                            else
                            {
                                Interface.CurrentControls[i].AnalogState = (double)Math.Sign(axisState);
                            }
                        }
                        else
                        {
                            if (Math.Sign(axisState) == Math.Sign(Interface.CurrentControls[i].Direction))
                            {
                                axisState = Math.Abs(axisState);
                                if (axisState < Interface.CurrentOptions.JoystickAxisThreshold)
                                {
                                    axisState = 0.0f;
                                }
                                else if (Interface.CurrentOptions.JoystickAxisThreshold != 1.0)
                                {
                                    axisState = (float)((axisState - Interface.CurrentOptions.JoystickAxisThreshold) / (1.0 - Interface.CurrentOptions.JoystickAxisThreshold));
                                }
                                else
                                {
                                    axisState = 1.0f;
                                }
                                if (Interface.CurrentControls[i].DigitalState == Interface.DigitalControlState.Released | Interface.CurrentControls[i].DigitalState == Interface.DigitalControlState.ReleasedAcknowledged)
                                {
                                    if (axisState > 0.67)
                                    {
                                        Interface.CurrentControls[i].DigitalState = Interface.DigitalControlState.Pressed;
                                    }
                                }
                                else
                                {
                                    if (axisState < 0.33)
                                    {
                                        Interface.CurrentControls[i].DigitalState = Interface.DigitalControlState.Released;
                                    }
                                }
                            }
                        }
                    }
                    break;

                case Interface.JoystickComponent.Button:
                    //Load the current state
                    var buttonState = JoystickManager.GetButton(currentDevice, Interface.CurrentControls[i].Element);
                    //Test whether the state is the same as the last frame
                    if (buttonState.ToString() != Interface.CurrentControls[i].LastState)
                    {
                        if (buttonState == ButtonState.Pressed)
                        {
                            Interface.CurrentControls[i].AnalogState  = 1.0;
                            Interface.CurrentControls[i].DigitalState = Interface.DigitalControlState.Pressed;
                            AddControlRepeat(i);
                        }
                        else
                        {
                            Interface.CurrentControls[i].AnalogState  = 0.0;
                            Interface.CurrentControls[i].DigitalState = Interface.DigitalControlState.Released;
                            RemoveControlRepeat(i);
                        }
                        //Store the state
                        Interface.CurrentControls[i].LastState = buttonState.ToString();
                    }
                    break;

                case Interface.JoystickComponent.Hat:
                    //Load the current state
                    var hatState = JoystickManager.GetHat(currentDevice, Interface.CurrentControls[i].Element).Position;
                    //Test if the state is the same as last frame
                    if (hatState.ToString() != Interface.CurrentControls[i].LastState)
                    {
                        if ((int)hatState == Interface.CurrentControls[i].Direction)
                        {
                            Interface.CurrentControls[i].AnalogState  = 1.0;
                            Interface.CurrentControls[i].DigitalState = Interface.DigitalControlState.Pressed;
                            AddControlRepeat(i);
                        }
                        else
                        {
                            Interface.CurrentControls[i].AnalogState  = 0.0;
                            Interface.CurrentControls[i].DigitalState = Interface.DigitalControlState.Released;
                            RemoveControlRepeat(i);
                        }
                        //Store the state
                        Interface.CurrentControls[i].LastState = hatState.ToString();
                    }
                    break;
                }
            }
        }
Esempio n. 5
0
        public void Poll()
        {
            for (int i = 0; i < 4; i++)
            {
                JoystickCapabilities caps = Joystick.GetCapabilities(i);
                if (caps.IsConnected && joysticks[i].Description == DisconnectedName)
                {
                    // New joystick connected
                    joysticks[i] = new LegacyJoystickDevice(
                        i,
                        caps.AxisCount + 2 * caps.HatCount,
                        caps.ButtonCount);
                    //device.Description = Joystick.GetName(i);
                    joysticks[i].Description = ConnectedName;
                }
                else if (!caps.IsConnected && joysticks[i].Description != DisconnectedName)
                {
                    // Joystick disconnected
                    joysticks[i]             = new LegacyJoystickDevice(i, 0, 0);
                    joysticks[i].Description = DisconnectedName;
                }

                JoystickState state = Joystick.GetState(i);
                for (int axis_index = 0; axis_index < caps.AxisCount; axis_index++)
                {
                    JoystickAxis axis = JoystickAxis.Axis0 + axis_index;
                    joysticks[i].SetAxis(axis, state.GetAxis(axis));
                }
                for (int button_index = 0; button_index < caps.ButtonCount; button_index++)
                {
                    JoystickButton button = JoystickButton.Button0 + button_index;
                    joysticks[i].SetButton(button, state.GetButton(button) == ButtonState.Pressed);
                }
                for (int hat_index = 0; hat_index < caps.HatCount; hat_index++)
                {
                    // LegacyJoystickDriver report hats as pairs of axes
                    // Make sure we have enough axes left for this mapping
                    int axis_index = caps.AxisCount + 2 * hat_index;
                    if (axis_index < JoystickState.MaxAxes)
                    {
                        JoystickHat      hat       = JoystickHat.Hat0 + hat_index;
                        JoystickHatState hat_state = state.GetHat(hat);
                        JoystickAxis     axis      = JoystickAxis.Axis0 + axis_index;
                        float            x         = 0;
                        float            y         = 0;
                        if (hat_state.IsDown)
                        {
                            y--;
                        }
                        if (hat_state.IsUp)
                        {
                            y++;
                        }
                        if (hat_state.IsLeft)
                        {
                            x--;
                        }
                        if (hat_state.IsRight)
                        {
                            x++;
                        }

                        joysticks[i].SetAxis(axis, x);
                        joysticks[i].SetAxis(axis + 1, y);
                    }
                }
            }
        }
Esempio n. 6
0
        // attached joysticks
        private void pictureboxJoysticks_Paint(object sender, PaintEventArgs e)
        {
            this.DoubleBuffered = true;
            int device = -1;

            Interface.JoystickComponent component = Interface.JoystickComponent.Invalid;
            int element   = -1;
            int direction = -1;

            Interface.CommandType type = Interface.CommandType.Digital;
            if (this.Tag == null & listviewControls.SelectedIndices.Count == 1)
            {
                int j = listviewControls.SelectedIndices[0];
                if (Interface.CurrentControls[j].Method == Interface.ControlMethod.Joystick)
                {
                    device    = Interface.CurrentControls[j].Device;
                    component = Interface.CurrentControls[j].Component;
                    element   = Interface.CurrentControls[j].Element;
                    direction = Interface.CurrentControls[j].Direction;
                    type      = Interface.CurrentControls[j].InheritedType;
                }
            }

            System.Globalization.CultureInfo Culture = System.Globalization.CultureInfo.InvariantCulture;
            e.Graphics.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            Font  f = new Font(this.Font.Name, 0.875f * this.Font.Size);
            float x = 2.0f, y = 2.0f;
            float threshold = ((float)trackbarJoystickAxisThreshold.Value - (float)trackbarJoystickAxisThreshold.Minimum) / (float)(trackbarJoystickAxisThreshold.Maximum - trackbarJoystickAxisThreshold.Minimum);

            for (int i = 0; i < Joysticks.AttachedJoysticks.Length; i++)
            {
                //Get the current joystick state
                var capabilities = Joystick.GetCapabilities(Joysticks.AttachedJoysticks[i].OpenTKHandle);
                var state        = Joystick.GetState(Joysticks.AttachedJoysticks[i].OpenTKHandle);

                float w, h;
                if (JoystickImage != null)
                {
                    e.Graphics.DrawImage(JoystickImage, x, y);
                    w = (float)JoystickImage.Width;
                    h = (float)JoystickImage.Height;
                    if (h < 64.0f)
                    {
                        h = 64.0f;
                    }
                }
                else
                {
                    w = 64.0f; h = 64.0f;
                    e.Graphics.DrawRectangle(new Pen(labelControlsTitle.BackColor), x, y, w, h);
                }
                {                 // joystick number
                    e.Graphics.FillEllipse(Brushes.Gold, x + w - 16.0f, y, 16.0f, 16.0f);
                    e.Graphics.DrawEllipse(Pens.Black, x + w - 16.0f, y, 16.0f, 16.0f);
                    string t = (i + 1).ToString(Culture);
                    SizeF  s = e.Graphics.MeasureString(t, f);
                    e.Graphics.DrawString(t, f, Brushes.Black, x + w - 8.0f - 0.5f * s.Width, y + 8.0f - 0.5f * s.Height);
                }
                {                 // joystick name
                    e.Graphics.DrawString(Joysticks.AttachedJoysticks[i].Name, this.Font, Brushes.Black, x + w + 8.0f, y);
                }
                if (OpenTK.Configuration.RunningOnSdl2)
                {
                    //HACK: Control configuration doesn't work in-form on SDL2
                    string error = Interface.GetInterfaceString("errors_controls_ingame");
                    if (OpenTK.Configuration.RunningOnSdl2)
                    {
                        error = error.Replace("[platform]", "SDL2");
                    }
                    e.Graphics.DrawString(error, this.Font, Brushes.Black, x + w + 8.0f, y + 30.0f);
                    return;
                }
                float m;
                if (groupboxJoysticks.Enabled)
                {
                    m = x;
                    Pen p  = new Pen(Color.DarkGoldenrod, 2.0f);
                    Pen ps = new Pen(Color.Firebrick, 2.0f);
                    {                     // first row
                        float u = x + w + 8.0f;
                        float v = y + 24.0f;
                        float g = h - 24.0f;
                        {                         // hats
                            int n = capabilities.HatCount;
                            for (int j = 0; j < n; j++)
                            {
                                if (device == i & component == Interface.JoystickComponent.Hat & element == j)
                                {
                                    e.Graphics.DrawEllipse(ps, u, v, g, g);
                                }
                                else
                                {
                                    e.Graphics.DrawEllipse(p, u, v, g, g);
                                }
                                string t = "H" + (j + 1).ToString(Culture);
                                SizeF  s = e.Graphics.MeasureString(t, f);
                                e.Graphics.DrawString(t, f, Brushes.Black, u + 0.5f * (g - s.Width), v + 0.5f * (g - s.Height));
                                JoystickHatState aa = state.GetHat((JoystickHat)j);
                                HatPosition      a  = aa.Position;
                                if (a != HatPosition.Centered)
                                {
                                    double rx = 0.0;
                                    double ry = 0.0;
                                    switch (a)
                                    {
                                    case HatPosition.Up:
                                        rx = 0.0;
                                        ry = -1.0;
                                        break;

                                    case HatPosition.Down:
                                        rx = 0.0;
                                        ry = 1.0;
                                        break;

                                    case HatPosition.Left:
                                        rx = -1.0;
                                        ry = 0.0;
                                        break;

                                    case HatPosition.Right:
                                        rx = 1.0;
                                        ry = 0.0;
                                        break;

                                    case HatPosition.UpLeft:
                                        rx = -1.0;
                                        ry = -1.0;
                                        break;

                                    case HatPosition.UpRight:
                                        rx = 1.0;
                                        ry = -1.0;
                                        break;

                                    case HatPosition.DownLeft:
                                        rx = -1.0;
                                        ry = 1.0;
                                        break;

                                    case HatPosition.DownRight:
                                        rx = 1.0;
                                        ry = 1.0;
                                        break;
                                    }

                                    double rt = rx * rx + ry * ry;
                                    rt  = 1.0 / Math.Sqrt(rt);
                                    rx *= rt; ry *= rt;
                                    float dx = (float)(0.5 * rx * (g - 8.0));
                                    float dy = (float)(0.5 * ry * (g - 8.0));
                                    e.Graphics.FillEllipse(Brushes.White, u + 0.5f * g + dx - 4.0f, v + 0.5f * g + dy - 4.0f, 8.0f, 8.0f);
                                    e.Graphics.DrawEllipse(new Pen(Color.Firebrick, 2.0f), u + 0.5f * g + dx - 4.0f, v + 0.5f * g + dy - 4.0f, 8.0f, 8.0f);
                                }
                                if (device == i & component == Interface.JoystickComponent.Hat & element == j)
                                {
                                    double rx = ((HatPosition)direction & HatPosition.Left) != 0 ? -1.0 : ((HatPosition)direction & HatPosition.Right) != 0 ? 1.0 : 0.0;
                                    double ry = ((HatPosition)direction & HatPosition.Up) != 0 ? -1.0 : ((HatPosition)direction & HatPosition.Down) != 0 ? 1.0 : 0.0;
                                    double rt = rx * rx + ry * ry;
                                    rt  = 1.0 / Math.Sqrt(rt);
                                    rx *= rt; ry *= rt;
                                    float dx = (float)(0.5 * rx * (g - 8.0));
                                    float dy = (float)(0.5 * ry * (g - 8.0));
                                    e.Graphics.FillEllipse(Brushes.Firebrick, u + 0.5f * g + dx - 2.0f, v + 0.5f * g + dy - 2.0f, 4.0f, 4.0f);
                                }
                                u += g + 8.0f;
                            }
                        }
                        if (u > m)
                        {
                            m = u;
                        }
                    }

                    {                     // second row
                        float u = x;
                        float v = y + h + 8.0f;
                        {                         // axes
                            int   n = capabilities.AxisCount;
                            float g = (float)pictureboxJoysticks.ClientRectangle.Height - v - 2.0f;
                            for (int j = 0; j < n; j++)
                            {
                                float r  = state.GetAxis((JoystickAxis)j);
                                float r0 = r < 0.0f ? r : 0.0f;
                                float r1 = r > 0.0f ? r : 0.0f;
                                if ((float)Math.Abs((double)r) < threshold)
                                {
                                    e.Graphics.FillRectangle(Brushes.RosyBrown, u, v + 0.5f * g - 0.5f * r1 * g, 16.0f, 0.5f * g * (r1 - r0));
                                }
                                else
                                {
                                    e.Graphics.FillRectangle(Brushes.Firebrick, u, v + 0.5f * g - 0.5f * r1 * g, 16.0f, 0.5f * g * (r1 - r0));
                                }
                                if (device == i & component == Interface.JoystickComponent.Axis & element == j)
                                {
                                    if (direction == -1 & type != Interface.CommandType.AnalogFull)
                                    {
                                        e.Graphics.DrawRectangle(p, u, v, 16.0f, g);
                                        e.Graphics.DrawRectangle(ps, u, v + 0.5f * g, 16.0f, 0.5f * g);
                                    }
                                    else if (direction == 1 & type != Interface.CommandType.AnalogFull)
                                    {
                                        e.Graphics.DrawRectangle(p, u, v, 16.0f, g);
                                        e.Graphics.DrawRectangle(ps, u, v, 16.0f, 0.5f * g);
                                    }
                                    else
                                    {
                                        e.Graphics.DrawRectangle(ps, u, v, 16.0f, g);
                                    }
                                }
                                else
                                {
                                    e.Graphics.DrawRectangle(p, u, v, 16.0f, g);
                                }
                                e.Graphics.DrawLine(p, u, v + (0.5f - 0.5f * threshold) * g, u + 16.0f, v + (0.5f - 0.5f * threshold) * g);
                                e.Graphics.DrawLine(p, u, v + (0.5f + 0.5f * threshold) * g, u + 16.0f, v + (0.5f + 0.5f * threshold) * g);
                                string t = "A" + (j + 1).ToString(Culture);
                                SizeF  s = e.Graphics.MeasureString(t, f);
                                e.Graphics.DrawString(t, f, Brushes.Black, u + 0.5f * (16.0f - s.Width), v + g - s.Height - 2.0f);
                                u += 24.0f;
                            }
                        }

                        {                         // buttons
                            int   n = capabilities.ButtonCount;
                            float g = (float)0.5f * (pictureboxJoysticks.ClientRectangle.Height - v - 10.0f);
                            for (int j = 0; j < n; j++)
                            {
                                bool  q  = state.GetButton((JoystickButton)j) != 0;
                                float dv = (float)(j & 1) * (g + 8.0f);
                                if (q)
                                {
                                    e.Graphics.FillRectangle(Brushes.Firebrick, u, v + dv, g, g);
                                }
                                if (device == i & component == Interface.JoystickComponent.Button & element == j)
                                {
                                    e.Graphics.DrawRectangle(ps, u, v + dv, g, g);
                                }
                                else
                                {
                                    e.Graphics.DrawRectangle(p, u, v + dv, g, g);
                                }
                                string t = "B" + (j + 1).ToString(Culture);
                                SizeF  s = e.Graphics.MeasureString(t, f);
                                e.Graphics.DrawString(t, f, Brushes.Black, u + 0.5f * (g - s.Width), v + dv + 0.5f * (g - s.Height));
                                if ((j & 1) != 0 | j == n - 1)
                                {
                                    u += g + 8.0f;
                                }
                            }
                        }

                        if (u > m)
                        {
                            m = u;
                        }
                    }
                }
                else
                {
                    m = x + w + 64.0f;
                }
                x = m + 8.0f;
            }
        }
        public GamePadState GetState(int index)
        {
            JoystickState joy = Joystick.GetState(index);
            GamePadState  pad = new GamePadState();

            if (joy.IsConnected)
            {
                pad.SetConnected(true);
                pad.SetPacketNumber(joy.PacketNumber);

                GamePadConfiguration configuration = GetConfiguration(Joystick.GetGuid(index));

                foreach (GamePadConfigurationItem map in configuration)
                {
                    switch (map.Source.Type)
                    {
                    case ConfigurationType.Axis:
                    {
                        // JoystickAxis -> Buttons/GamePadAxes mapping
                        JoystickAxis source_axis = map.Source.Axis;
                        short        value       = joy.GetAxisRaw(source_axis);

                        switch (map.Target.Type)
                        {
                        case ConfigurationType.Axis:
                            pad.SetAxis(map.Target.Axis, value);
                            break;

                        case ConfigurationType.Button:
                            // Todo: if SDL2 GameController config is ever updated to
                            // distinguish between negative/positive axes, then remove
                            // Math.Abs below.
                            // Button is considered press when the axis is >= 0.5 from center
                            pad.SetButton(map.Target.Button, Math.Abs(value) >= short.MaxValue >> 1);
                            break;
                        }
                    }
                    break;

                    case ConfigurationType.Button:
                    {
                        // JoystickButton -> Buttons/GamePadAxes mapping
                        JoystickButton source_button = map.Source.Button;
                        bool           pressed       = joy.GetButton(source_button) == ButtonState.Pressed;

                        switch (map.Target.Type)
                        {
                        case ConfigurationType.Axis:
                            // Todo: if SDL2 GameController config is ever updated to
                            // distinguish between negative/positive axes, then update
                            // the following line to support both.
                            short value = pressed ?
                                          short.MaxValue :
                                          (map.Target.Axis & (GamePadAxes.LeftTrigger | GamePadAxes.RightTrigger)) != 0 ?
                                          short.MinValue :
                                          (short)0;
                            pad.SetAxis(map.Target.Axis, value);
                            break;

                        case ConfigurationType.Button:
                            pad.SetButton(map.Target.Button, pressed);
                            break;
                        }
                    }
                    break;

                    case ConfigurationType.Hat:
                    {
                        // JoystickHat -> Buttons/GamePadAxes mapping
                        JoystickHat      source_hat = map.Source.Hat;
                        JoystickHatState state      = joy.GetHat(source_hat);

                        bool pressed = false;
                        switch (map.Source.HatPosition)
                        {
                        case HatPosition.Down:
                            pressed = state.IsDown;
                            break;

                        case HatPosition.Up:
                            pressed = state.IsUp;
                            break;

                        case HatPosition.Left:
                            pressed = state.IsLeft;
                            break;

                        case HatPosition.Right:
                            pressed = state.IsRight;
                            break;
                        }

                        switch (map.Target.Type)
                        {
                        case ConfigurationType.Axis:
                            // Todo: if SDL2 GameController config is ever updated to
                            // distinguish between negative/positive axes, then update
                            // the following line to support both.
                            short value = pressed ?
                                          short.MaxValue :
                                          (map.Target.Axis & (GamePadAxes.LeftTrigger | GamePadAxes.RightTrigger)) != 0 ?
                                          short.MinValue :
                                          (short)0;
                            pad.SetAxis(map.Target.Axis, value);
                            break;

                        case ConfigurationType.Button:
                            pad.SetButton(map.Target.Button, pressed);
                            break;
                        }
                    }
                    break;
                    }
                }
            }

            return(pad);
        }
Esempio n. 8
0
        void PollJoystick(LinuxJoystickDetails js)
        {
            unsafe
            {
                const int   EventCount = 32;
                InputEvent *events     = stackalloc InputEvent[EventCount];

                long length = 0;
                while (true)
                {
                    length = (long)Libc.read(js.FileDescriptor, (void *)events, (UIntPtr)(sizeof(InputEvent) * EventCount));
                    if (length <= 0)
                    {
                        break;
                    }

                    // Only mark the joystick as connected when we actually start receiving events.
                    // Otherwise, the Xbox wireless receiver will register 4 joysticks even if no
                    // actual joystick is connected to the receiver.
                    js.Caps.SetIsConnected(true);
                    js.State.SetIsConnected(true);

                    length /= sizeof(InputEvent);
                    for (int i = 0; i < length; i++)
                    {
                        InputEvent *e = events + i;
                        switch (e->Type)
                        {
                        case EvdevType.ABS:
                        {
                            AxisInfo axis;
                            if (js.AxisMap.TryGetValue((EvdevAxis)e->Code, out axis))
                            {
                                if (axis.Info.Maximum > axis.Info.Minimum)
                                {
                                    if (e->Code >= (int)EvdevAxis.HAT0X && e->Code <= (int)EvdevAxis.HAT3Y)
                                    {
                                        // We currently treat analogue hats as digital hats
                                        // to maintain compatibility with SDL2. We can do
                                        // better than this, however.
                                        JoystickHat      hat = JoystickHat.Hat0 + (e->Code - (int)EvdevAxis.HAT0X) / 2;
                                        JoystickHatState pos = js.State.GetHat(hat);
                                        int xy_axis          = (int)axis.Axis & 0x1;
                                        switch (xy_axis)
                                        {
                                        case 0:
                                            // X-axis
                                            pos = TranslateHat(
                                                e->Value.CompareTo(0) + 1,
                                                pos.IsUp ? 0 : pos.IsDown ? 2 : 1);
                                            break;

                                        case 1:
                                            // Y-axis
                                            pos = TranslateHat(
                                                pos.IsLeft ? 0 : pos.IsRight ? 2 : 1,
                                                e->Value.CompareTo(0) + 1);
                                            break;
                                        }

                                        js.State.SetHat(hat, pos);
                                    }
                                    else
                                    {
                                        // This axis represents a regular axis or trigger
                                        js.State.SetAxis(
                                            axis.Axis,
                                            (short)Common.HidHelper.ScaleValue(e->Value,
                                                                               axis.Info.Minimum, axis.Info.Maximum,
                                                                               short.MinValue, short.MaxValue));
                                    }
                                }
                            }
                            break;
                        }

                        case EvdevType.KEY:
                        {
                            JoystickButton button;
                            if (js.ButtonMap.TryGetValue((EvdevButton)e->Code, out button))
                            {
                                js.State.SetButton(button, e->Value != 0);
                            }
                            break;
                        }
                        }

                        // Create a serial number (total seconds in 24.8 fixed point format)
                        int sec    = (int)((long)e->Time.Seconds & 0xffffffff);
                        int msec   = (int)e->Time.MicroSeconds / 1000;
                        int packet =
                            ((sec & 0x00ffffff) << 24) |
                            Common.HidHelper.ScaleValue(msec, 0, 1000, 0, 255);
                        js.State.SetPacketNumber(packet);
                    }
                }
            }
        }
Esempio n. 9
0
        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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.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 = CSound管理.rc演奏用タイマ.nシステム時刻ms,                                 // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。
                            };
                            this.list入力イベント.Add(stevent);

                            this.bButtonState[nWay]  = false;
                            this.bButtonPullUp[nWay] = true;
                        }
                    }
                    #endregion
                    //-----------------------------
                    #endregion
                }
            }
        }
Esempio n. 10
0
 static public VectorI2 GetVectorI2(this JoystickHatState item)
 {
     return(item.Position.GetVectorI2());
 }
Esempio n. 11
0
        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 ControllerHandler(Dictionary <string, ButtonState> oldPsButtons, int freq, string mode, byte controllmode = 0)
        {
            _freq = freq;

            JoystickState joyStick = Joystick.GetState(0);

            if (joyStick.IsConnected)
            {
                _xl        = Convert.ToInt16(Math.Floor(joyStick.GetAxis(JoystickAxis.Axis0) * 100));      // Left  stick sideways
                _yl        = Convert.ToInt16(Math.Floor(joyStick.GetAxis(JoystickAxis.Axis1) * 100 * -1)); // Left  stick updown
                _xr        = Convert.ToInt16(Math.Floor(joyStick.GetAxis(JoystickAxis.Axis3) * 100 * -1)); // Right stick sideways
                _yr        = Convert.ToInt16(Math.Floor(joyStick.GetAxis(JoystickAxis.Axis4) * 100));      // Right stick updown
                _cross     = joyStick.GetButton(JoystickButton.Button0);                                   // Cross
                _circle    = joyStick.GetButton(JoystickButton.Button1);                                   // Circle
                _triangle  = joyStick.GetButton(JoystickButton.Button3);                                   // Triangle
                _square    = joyStick.GetButton(JoystickButton.Button2);                                   // Square
                _start     = joyStick.GetButton(JoystickButton.Button7);                                   // Start
                _selectB   = joyStick.GetButton(JoystickButton.Button6);                                   // Select
                _l1        = joyStick.GetButton(JoystickButton.Button4);                                   // L1
                _r1        = joyStick.GetButton(JoystickButton.Button5);                                   // R1
                _l3        = joyStick.GetButton(JoystickButton.Button8);                                   // L3
                _hatSwitch = joyStick.GetHat(JoystickHat.Hat0);                                            // hatSwitch

//                Console.WriteLine("" +
//                                  "x left: {0}\n" +
//                                  "y left: {1}\n" +
//                                  "x right: {2}\n" +
//                                  "y right: {3}\n" +
//                                  "Speed: {4}\n" +
//                                  "Wheels: {5}\n" +
//                                  "ControllMode: {6}\n"
//                    , _xl, _yl, _xr, _yr, _speed * 2.55, _wheelPos, _controllMode);
                _psButtons = new Dictionary <string, ButtonState>
                {
                    { "cross", _cross },
                    { "circle", _circle },
                    { "triangle", _triangle },
                    { "square", _square },
                    { "start", _start },
                    { "select", _selectB },
                    { "l1", _l1 },
                    { "r1", _r1 },
                    { "l3", _l3 }
                };
//                foreach (var button in _psButtons)
//                {
//                    Console.WriteLine(button.Key + ": " + button.Value);
//                }
//                Console.WriteLine();

                if (oldPsButtons != null)
                {
                    #region Speed controll code

                    #region Left stick code

                    if (_controllMode == 1)
                    {
                        // Backwards
                        if (_yl > 5)
                        {
                            _speed = _yl;
                        }
                        else if (_yl < 5 && _speed < 1)
                        {
                            _speed += 5;
                        }
                        // Forwards
                        if (_yl < -5)
                        {
                            _speed = _yl;
                        }
                        else if (_yl > -5 && _speed > 1)
                        {
                            _speed -= 5;
                        }
                        if (_speed >= -5 && _speed <= 5)
                        {
                            _speed = 0;                              // Fix for absolute stop of engines
                        }
                    }

                    #endregion

                    #region cross+circle

                    if (_controllMode == 2)
                    {
                        if (_cross == ButtonState.Pressed && _hatSwitch.Position == HatPosition.Centered &&
                            !(_speed == 70 || _speed > 70))
                        {
                            _speed += 10;
                        }
                        else if (_cross == ButtonState.Pressed && _hatSwitch.IsUp && _speed != 100)
                        {
                            _speed += 10;
                        }
                        else if (_cross == ButtonState.Pressed && _hatSwitch.Position == HatPosition.Centered && _speed > 70)
                        {
                            _speed -= 10;
                        }
                        else if (_cross == ButtonState.Released && _speed > 0)
                        {
                            _speed = 0;
                        }
                        else if (_circle == ButtonState.Pressed && !(_speed == -70 || _speed < -70))
                        {
                            _speed -= 10;
                        }
                        else if (_circle == ButtonState.Pressed && _hatSwitch.IsDown && _speed != -100)
                        {
                            _speed -= 10;
                        }

                        else if (_circle == ButtonState.Pressed && _hatSwitch.Position == HatPosition.Centered &&
                                 _speed < -70)
                        {
                            _speed += 10;
                        }
                        else if (_circle == ButtonState.Released && _speed < 0)
                        {
                            _speed = 0;
                        }
                    }

                    #endregion

                    #endregion
                    #region steering controll code
                    #region leftstick

                    if (_controllMode == 1)
                    {
                        // Backwards
                        if (_xl > 5)
                        {
                            _wheelPos1 = _xl;
                        }
                        else if (_xl < 5 && _wheelPos1 > 1)
                        {
                            _wheelPos1 = 0;
                        }
                        // Forwards
                        if (_xl < -5)
                        {
                            _wheelPos2 = _xl;
                        }
                        else if (_xl > -5 && _wheelPos2 < -1)
                        {
                            _wheelPos2 = 0;
                        }
                        if (_xl == 0)
                        {
                            _wheelPos1 = 0;
                            _wheelPos2 = 0;
                        }
                    }

                    #endregion

                    #region cross+circle

                    if (_controllMode == 2)
                    {
                        if (_hatSwitch.IsRight && _wheelPos1 < 50)
                        {
                            _wheelPos1 += 10;
                        }
                        else if (_hatSwitch.Position == HatPosition.Centered && _wheelPos1 > 0)
                        {
                            _wheelPos1 = 0;
                        }
                        if (_hatSwitch.IsLeft && _wheelPos2 < 50)
                        {
                            _wheelPos2 += 10;
                        }
                        else if (_hatSwitch.Position == HatPosition.Centered && _wheelPos2 > 0)
                        {
                            _wheelPos2 = 0;
                        }
                    }

                    #endregion

                    #endregion

                    #region pan_tilt
                    #region servoPosY
                    if (_yr > 5)
                    {
                        servoPosY = _yr;
                    }

                    else if (_yr < 5 && servoPosY > 1)
                    {
                        servoPosY = 0;
                    }
                    if (_yr < -5)
                    {
                        servoPosY = _yr;
                    }
                    else if (_yr > -5 && servoPosY < -1)
                    {
                        servoPosY = 0;
                    }
                    if (_yr == 0)
                    {
                        servoPosY = 0;
                    }
                    #endregion
                    #region servoPosX
                    if (_xr > 5)
                    {
                        servoPosX = _xr;
                    }
                    else if (_xr < 5 && servoPosX > 1)
                    {
                        servoPosX = 0;
                    }

                    if (_xr < -5)
                    {
                        servoPosX = _xr;
                    }
                    else if (_xr > -5 && servoPosX < -1)
                    {
                        servoPosX = 0;
                    }
                    if (_xr == 0)
                    {
                        servoPosX = 0;
                    }
                    #endregion
                    #endregion
                    #region Button checks

                    // Gets all the buttons out of the oldpsbuttons to see if it was pressed
                    ButtonState selectOld, startOld, triangleOld, squareOld, l1Old, r1Old, l3Old;
                    oldPsButtons.TryGetValue("select", out selectOld);
                    oldPsButtons.TryGetValue("start", out startOld);
                    oldPsButtons.TryGetValue("triangle", out triangleOld);
                    oldPsButtons.TryGetValue("square", out squareOld);
                    oldPsButtons.TryGetValue("l1", out l1Old);
                    oldPsButtons.TryGetValue("r1", out r1Old);
                    oldPsButtons.TryGetValue("l1", out l3Old);



                    if (_start == ButtonState.Released && startOld == ButtonState.Pressed)
                    {
                        _resetmh   = true;
                        _speed     = 0;
                        _wheelPos1 = 0;
                        _wheelPos2 = 0;
                    }

                    #endregion
                }
            }
        }