public void State_CanWaitForStateChangeWithinGivenAmountOfTime()
    {
        var gamepad = InputSystem.AddDevice <Gamepad>();

        var          monitorFired       = false;
        var          timeoutFired       = false;
        double?      receivedTime       = null;
        int?         receivedTimerIndex = null;
        InputControl receivedControl    = null;

        var monitor = InputSystem.AddStateChangeMonitor(gamepad.leftStick,
                                                        (control, time, monitorIndex) =>
        {
            Assert.That(!monitorFired);
            monitorFired = true;
        }, timerExpiredCallback:
                                                        (control, time, monitorIndex, timerIndex) =>
        {
            Assert.That(!timeoutFired);
            timeoutFired       = true;
            receivedTime       = time;
            receivedTimerIndex = timerIndex;
            receivedControl    = control;
        });

        // Add and immediately expire timeout.
        InputSystem.AddStateChangeMonitorTimeout(gamepad.leftStick, monitor, testRuntime.currentTime + 1,
                                                 timerIndex: 1234);
        testRuntime.currentTime += 2;
        InputSystem.Update();

        Assert.That(timeoutFired);
        Assert.That(!monitorFired);
        Assert.That(receivedTimerIndex.Value, Is.EqualTo(1234));
        Assert.That(receivedTime.Value, Is.EqualTo(testRuntime.currentTime).Within(0.00001));
        Assert.That(receivedControl, Is.SameAs(gamepad.leftStick));

        timeoutFired       = false;
        receivedTimerIndex = null;
        receivedTime       = null;

        // Add timeout and obsolete it by state change. Then advance past timeout time
        // and make sure we *don't* get a notification.
        InputSystem.AddStateChangeMonitorTimeout(gamepad.leftStick, monitor, testRuntime.currentTime + 1,
                                                 timerIndex: 4321);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftStick = Vector2.one
        });
        InputSystem.Update();

        Assert.That(monitorFired);
        Assert.That(!timeoutFired);

        testRuntime.currentTime += 2;
        InputSystem.Update();

        Assert.That(!timeoutFired);

        // Add and remove timeout. Then advance past timeout time and make sure we *don't*
        // get a notification.
        InputSystem.AddStateChangeMonitorTimeout(gamepad.leftStick, monitor, testRuntime.currentTime + 1,
                                                 timerIndex: 1423);
        InputSystem.RemoveStateChangeMonitorTimeout(monitor, timerIndex: 1423);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftStick = Vector2.one
        });
        InputSystem.Update();

        Assert.That(!timeoutFired);
    }
Пример #2
0
    public void Remote_CanConnectInputSystemsOverEditorPlayerConnection()
    {
#if UNITY_EDITOR
        // In the editor, RemoteInputPlayerConnection is a scriptable singleton. Creating multiple instances of it
        // will cause an error messages - but will work nevertheless, so we expect those errors to let us run the test.
        // We call RemoteInputPlayerConnection.instance once to make sure that we an instance is created, and we get
        // a deterministic number of two errors.
        var instance = RemoteInputPlayerConnection.instance;
        UnityEngine.TestTools.LogAssert.Expect(LogType.Error, "ScriptableSingleton already exists. Did you query the singleton in a constructor?");
        UnityEngine.TestTools.LogAssert.Expect(LogType.Error, "ScriptableSingleton already exists. Did you query the singleton in a constructor?");
#endif
        var connectionToEditor = ScriptableObject.CreateInstance <RemoteInputPlayerConnection>();
        var connectionToPlayer = ScriptableObject.CreateInstance <RemoteInputPlayerConnection>();

        connectionToEditor.name = "ConnectionToEditor";
        connectionToPlayer.name = "ConnectionToPlayer";

        var fakeEditorConnection = new FakePlayerConnection {
            playerId = 0
        };
        var fakePlayerConnection = new FakePlayerConnection {
            playerId = 1
        };

        fakeEditorConnection.otherEnd = fakePlayerConnection;
        fakePlayerConnection.otherEnd = fakeEditorConnection;

        var observerEditor = new RemoteTestObserver();
        var observerPlayer = new RemoteTestObserver();

        // In the Unity API, "PlayerConnection" is the connection to the editor
        // and "EditorConnection" is the connection to the player. Seems counter-intuitive.
        connectionToEditor.Bind(fakePlayerConnection, true);
        connectionToPlayer.Bind(fakeEditorConnection, true);

        // Bind a local remote on the player side.
        var local = new InputRemoting(InputSystem.s_Manager);
        local.Subscribe(connectionToEditor);

        connectionToEditor.Subscribe(local);
        connectionToPlayer.Subscribe(observerEditor);
        connectionToEditor.Subscribe(observerPlayer);

        fakeEditorConnection.Send(RemoteInputPlayerConnection.kStartSendingMsg, null);

        var device = InputSystem.AddDevice <Gamepad>();
        InputSystem.QueueStateEvent(device, new GamepadState());
        InputSystem.Update();
        InputSystem.RemoveDevice(device);

        fakeEditorConnection.Send(RemoteInputPlayerConnection.kStopSendingMsg, null);

        // We should not obseve any messages for these, as we stopped sending!
        device = InputSystem.AddDevice <Gamepad>();
        InputSystem.QueueStateEvent(device, new GamepadState());
        InputSystem.Update();
        InputSystem.RemoveDevice(device);

        fakeEditorConnection.DisconnectAll();

        ////TODO: make sure that we also get the connection sequence right and send our initial layouts and devices
        Assert.That(observerEditor.messages, Has.Count.EqualTo(5));
        Assert.That(observerEditor.messages[0].type, Is.EqualTo(InputRemoting.MessageType.Connect));
        Assert.That(observerEditor.messages[1].type, Is.EqualTo(InputRemoting.MessageType.NewDevice));
        Assert.That(observerEditor.messages[2].type, Is.EqualTo(InputRemoting.MessageType.NewEvents));
        Assert.That(observerEditor.messages[3].type, Is.EqualTo(InputRemoting.MessageType.RemoveDevice));
        Assert.That(observerEditor.messages[4].type, Is.EqualTo(InputRemoting.MessageType.Disconnect));

        Assert.That(observerPlayer.messages, Has.Count.EqualTo(3));
        Assert.That(observerPlayer.messages[0].type, Is.EqualTo(InputRemoting.MessageType.Connect));
        Assert.That(observerPlayer.messages[1].type, Is.EqualTo(InputRemoting.MessageType.StartSending));
        Assert.That(observerPlayer.messages[2].type, Is.EqualTo(InputRemoting.MessageType.StopSending));

        ScriptableObject.Destroy(connectionToEditor);
        ScriptableObject.Destroy(connectionToPlayer);
    }
Пример #3
0
    public void Devices_SupportsSwitchNpad()
    {
        var device = InputSystem.AddDevice(
            new InputDeviceDescription
        {
            interfaceName = "Switch",
            manufacturer  = "Nintendo",
            product       = "Wireless Controller",
        });

        Assert.That(device, Is.TypeOf <NPad>());
        var controller = (NPad)device;

        InputSystem.QueueStateEvent(controller,
                                    new NPadInputState
        {
            leftStick       = new Vector2(0.123f, 0.456f),
            rightStick      = new Vector2(0.789f, 0.987f),
            acceleration    = new Vector3(0.987f, 0.654f, 0.321f),
            attitude        = new Quaternion(0.111f, 0.222f, 0.333f, 0.444f),
            angularVelocity = new Vector3(0.444f, 0.555f, 0.666f),
        });
        InputSystem.Update();

        Assert.That(controller.leftStick.x.ReadValue(), Is.EqualTo(0.123).Within(0.00001));
        Assert.That(controller.leftStick.y.ReadValue(), Is.EqualTo(0.456).Within(0.00001));
        Assert.That(controller.rightStick.x.ReadValue(), Is.EqualTo(0.789).Within(0.00001));
        Assert.That(controller.rightStick.y.ReadValue(), Is.EqualTo(0.987).Within(0.00001));

        Assert.That(controller.acceleration.x.ReadValue(), Is.EqualTo(0.987).Within(0.00001));
        Assert.That(controller.acceleration.y.ReadValue(), Is.EqualTo(0.654).Within(0.00001));
        Assert.That(controller.acceleration.z.ReadValue(), Is.EqualTo(0.321).Within(0.00001));

        Quaternion attitude = controller.attitude.ReadValue();

        Assert.That(attitude.x, Is.EqualTo(0.111).Within(0.00001));
        Assert.That(attitude.y, Is.EqualTo(0.222).Within(0.00001));
        Assert.That(attitude.z, Is.EqualTo(0.333).Within(0.00001));
        Assert.That(attitude.w, Is.EqualTo(0.444).Within(0.00001));

        Assert.That(controller.angularVelocity.x.ReadValue(), Is.EqualTo(0.444).Within(0.00001));
        Assert.That(controller.angularVelocity.y.ReadValue(), Is.EqualTo(0.555).Within(0.00001));
        Assert.That(controller.angularVelocity.z.ReadValue(), Is.EqualTo(0.666).Within(0.00001));

        AssertButtonPress(controller, new NPadInputState().WithButton(NPadInputState.Button.A), controller.buttonEast);
        AssertButtonPress(controller, new NPadInputState().WithButton(NPadInputState.Button.B), controller.buttonSouth);
        AssertButtonPress(controller, new NPadInputState().WithButton(NPadInputState.Button.X), controller.buttonNorth);
        AssertButtonPress(controller, new NPadInputState().WithButton(NPadInputState.Button.Y), controller.buttonWest);
        AssertButtonPress(controller, new NPadInputState().WithButton(NPadInputState.Button.StickL), controller.leftStickButton);
        AssertButtonPress(controller, new NPadInputState().WithButton(NPadInputState.Button.StickR), controller.rightStickButton);
        AssertButtonPress(controller, new NPadInputState().WithButton(NPadInputState.Button.L), controller.leftShoulder);
        AssertButtonPress(controller, new NPadInputState().WithButton(NPadInputState.Button.R), controller.rightShoulder);
        AssertButtonPress(controller, new NPadInputState().WithButton(NPadInputState.Button.ZL), controller.leftTrigger);
        AssertButtonPress(controller, new NPadInputState().WithButton(NPadInputState.Button.ZR), controller.rightTrigger);
        AssertButtonPress(controller, new NPadInputState().WithButton(NPadInputState.Button.Plus), controller.startButton);
        AssertButtonPress(controller, new NPadInputState().WithButton(NPadInputState.Button.Minus), controller.selectButton);
        AssertButtonPress(controller, new NPadInputState().WithButton(NPadInputState.Button.LSL), controller.leftSL);
        AssertButtonPress(controller, new NPadInputState().WithButton(NPadInputState.Button.LSR), controller.leftSR);
        AssertButtonPress(controller, new NPadInputState().WithButton(NPadInputState.Button.RSL), controller.rightSL);
        AssertButtonPress(controller, new NPadInputState().WithButton(NPadInputState.Button.RSR), controller.rightSR);
    }
Пример #4
0
    public void Samples_RebindingUI_SuppressingEventsDoesNotInterfereWithUIInput()
    {
        var keyboard = InputSystem.AddDevice <Keyboard>();

        var asset     = ScriptableObject.CreateInstance <InputActionAsset>();
        var actionMap = asset.AddActionMap("map");
        var action    = actionMap.AddAction("action", binding: "<Keyboard>/a");

        var canvasGO = new GameObject();

        canvasGO.SetActive(false);
        canvasGO.AddComponent <Canvas>();

        // Set up UI input module.
        var eventSystemGO = new GameObject();

        eventSystemGO.SetActive(false);
        var eventSystem   = eventSystemGO.AddComponent <TestEventSystem>();
        var uiInputModule = eventSystemGO.AddComponent <InputSystemUIInputModule>();
        var inputActions  = new DefaultInputActions().asset;

        uiInputModule.actionsAsset = inputActions;
        uiInputModule.submit       = InputActionReference.Create(inputActions["submit"]);

        var bindingButtonGO = new GameObject();

        bindingButtonGO.transform.parent = canvasGO.transform;
        var bindingButton = bindingButtonGO.AddComponent <Button>();

        var bindingLabelGO = new GameObject();

        bindingLabelGO.transform.parent = bindingButtonGO.transform;
        var bindingLabel = bindingLabelGO.AddComponent <Text>();

        var rebind = bindingButtonGO.AddComponent <RebindActionUI>();

        rebind.bindingId       = action.bindings[0].id.ToString();
        rebind.actionReference = InputActionReference.Create(action);
        rebind.bindingText     = bindingLabel;
        bindingButton.onClick.AddListener(rebind.StartInteractiveRebind);

        canvasGO.SetActive(true);
        eventSystemGO.SetActive(true);

        eventSystem.SetSelectedGameObject(bindingButtonGO);
        eventSystem.InvokeUpdate(); // Initial update switches the input module.

        Assert.That(rebind.ongoingRebind, Is.Null);
        Assert.That(bindingLabel.text, Is.EqualTo("A"));

        // As soon as the submit hits, the rebind starts -- which in turn enables suppression
        // of events. This means that the enter key release event will not reach the UI. The
        // UI should be fine with that.
        PressAndRelease(keyboard.enterKey);
        eventSystem.InvokeUpdate();

        Assert.That(rebind.ongoingRebind, Is.Not.Null);
        Assert.That(rebind.ongoingRebind.started, Is.True);
        Assert.That(rebind.ongoingRebind.candidates, Is.Empty);
        Assert.That(bindingLabel.text, Is.EqualTo("<Waiting...>"));
        Assert.That(inputActions["submit"].inProgress, Is.False);

        Press(keyboard.bKey);
        eventSystem.InvokeUpdate();

        Assert.That(rebind.ongoingRebind, Is.Not.Null);
        Assert.That(rebind.ongoingRebind.started, Is.True);
        Assert.That(rebind.ongoingRebind.candidates, Is.EquivalentTo(new[] { keyboard.bKey }));
        Assert.That(bindingLabel.text, Is.EqualTo("<Waiting...>"));
        Assert.That(inputActions["submit"].inProgress, Is.False);

        // Expire rebind wait time.
        currentTime += 1;
        InputSystem.Update();

        Assert.That(rebind.ongoingRebind, Is.Null);
        Assert.That(bindingLabel.text, Is.EqualTo("B"));
        Assert.That(inputActions["submit"].inProgress, Is.False);

        // Start another rebind via "Submit".
        PressAndRelease(keyboard.enterKey);
        eventSystem.InvokeUpdate();

        Assert.That(rebind.ongoingRebind, Is.Not.Null);
        Assert.That(rebind.ongoingRebind.started, Is.True);
        Assert.That(rebind.ongoingRebind.candidates, Is.Empty);
        Assert.That(bindingLabel.text, Is.EqualTo("<Waiting...>"));
    }
Пример #5
0
    public unsafe void Events_AreTimeslicedByDefault()
    {
        runtime.fixedUpdateIntervalInSeconds = 1.0 / 60; // 60 FPS.

        var gamepad = InputSystem.AddDevice <Gamepad>();

        var receivedEvents = new List <InputEvent>();

        InputSystem.onEvent +=
            eventPtr => receivedEvents.Add(*eventPtr.ToPointer());

        // First fixed update should just take everything.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.1234f
        }, 1);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.2345f
        }, 2);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.3456f
        }, 2.9);

        runtime.currentTime = 3;

        InputSystem.Update(InputUpdateType.Fixed);

        Assert.That(receivedEvents, Has.Count.EqualTo(3));
        Assert.That(receivedEvents[0].time, Is.EqualTo(1).Within(0.00001));
        Assert.That(receivedEvents[1].time, Is.EqualTo(2).Within(0.00001));
        Assert.That(receivedEvents[2].time, Is.EqualTo(2.9).Within(0.00001));
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.3456).Within(0.00001));

        Assert.That(InputUpdate.s_LastUpdateRetainedEventCount, Is.Zero);
        Assert.That(InputUpdate.s_LastFixedUpdateTime, Is.EqualTo(3).Within(0.0001));

        receivedEvents.Clear();

        // From now on, fixed updates should only take what falls in their slice.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.1234f
        }, 3 + 0.001);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.2345f
        }, 3 + 0.002);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.3456f
        }, 3 + 1.0 / 60 + 0.001);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.4567f
        }, 3 + 2 * (1.0 / 60) + 0.001);

        InputSystem.Update(InputUpdateType.Fixed);

        Assert.That(receivedEvents, Has.Count.EqualTo(2));
        Assert.That(receivedEvents[0].time, Is.EqualTo(3 + 0.001).Within(0.00001));
        Assert.That(receivedEvents[1].time, Is.EqualTo(3 + 0.002).Within(0.00001));
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.2345).Within(0.00001));

        Assert.That(InputUpdate.s_LastUpdateRetainedEventCount, Is.EqualTo(2));
        Assert.That(InputUpdate.s_LastFixedUpdateTime, Is.EqualTo(3 + 1.0 / 60).Within(0.0001));

        receivedEvents.Clear();

        InputSystem.Update(InputUpdateType.Fixed);

        Assert.That(receivedEvents, Has.Count.EqualTo(1));
        Assert.That(receivedEvents[0].time, Is.EqualTo(3 + 1.0 / 60 + 0.001).Within(0.00001));
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.3456).Within(0.00001));

        Assert.That(InputUpdate.s_LastUpdateRetainedEventCount, Is.EqualTo(1));
        Assert.That(InputUpdate.s_LastFixedUpdateTime, Is.EqualTo(3 + 2 * (1.0 / 60)).Within(0.0001));

        receivedEvents.Clear();

        InputSystem.Update(InputUpdateType.Fixed);

        Assert.That(receivedEvents, Has.Count.EqualTo(1));
        Assert.That(receivedEvents[0].time, Is.EqualTo(3 + 2 * (1.0 / 60) + 0.001).Within(0.00001));
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.4567).Within(0.00001));

        Assert.That(InputUpdate.s_LastUpdateRetainedEventCount, Is.Zero);
        Assert.That(InputUpdate.s_LastFixedUpdateTime, Is.EqualTo(3 + 3 * (1.0 / 60)).Within(0.0001));

        receivedEvents.Clear();

        InputSystem.Update(InputUpdateType.Fixed);

        Assert.That(receivedEvents, Has.Count.Zero);
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.4567).Within(0.00001));

        Assert.That(InputUpdate.s_LastUpdateRetainedEventCount, Is.Zero);
        Assert.That(InputUpdate.s_LastFixedUpdateTime, Is.EqualTo(3 + 4 * (1.0 / 60)).Within(0.0001));
    }
        private void SetupInputControl()
        {
            Debug.Assert(m_Control == null);
            Debug.Assert(m_NextControlOnDevice == null);
            Debug.Assert(!m_InputEventPtr.valid);

            // Nothing to do if we don't have a control path.
            if (string.IsNullOrEmpty(m_ControlPath))
            {
                return;
            }

            // Determine what type of device to work with.
            var layoutName = InputControlPath.TryGetDeviceLayout(m_ControlPath);

            if (layoutName == null)
            {
                Debug.LogError(
                    string.Format(
                        "Cannot determine device layout to use based on control path '{0}' used in {1} component",
                        m_ControlPath, GetType().Name), this);
                return;
            }

            // Try to find existing on-screen device that matches.
            var internedLayoutName = new InternedString(layoutName);
            var deviceInfoIndex    = -1;

            for (var i = 0; i < s_OnScreenDevices.length; ++i)
            {
                if (s_OnScreenDevices[i].device.m_Layout == internedLayoutName)
                {
                    deviceInfoIndex = i;
                    break;
                }
            }

            // If we don't have a matching one, create a new one.
            InputDevice device;

            if (deviceInfoIndex == -1)
            {
                // Try to create device.
                try
                {
                    device = InputSystem.AddDevice(layoutName);
                }
                catch (Exception exception)
                {
                    Debug.LogError(string.Format("Could not create device with layout '{0}' used in '{1}' component", layoutName,
                                                 GetType().Name));
                    Debug.LogException(exception);
                    return;
                }

                // Create event buffer.
                InputEventPtr eventPtr;
                var           buffer = StateEvent.From(device, out eventPtr, Allocator.Persistent);

                // Add to list.
                deviceInfoIndex = s_OnScreenDevices.Append(new OnScreenDeviceInfo
                {
                    eventPtr = eventPtr,
                    buffer   = buffer,
                    device   = device,
                });
            }
            else
            {
                device = s_OnScreenDevices[deviceInfoIndex].device;
            }

            // Try to find control on device.
            m_Control = InputControlPath.TryFindControl(device, m_ControlPath);
            if (m_Control == null)
            {
                Debug.LogError(
                    string.Format(
                        "Cannot find control with path '{0}' on device of type '{1}' referenced by component '{2}'",
                        m_ControlPath, layoutName, GetType().Name), this);

                // Remove the device, if we just created one.
                if (s_OnScreenDevices[deviceInfoIndex].firstControl == null)
                {
                    s_OnScreenDevices[deviceInfoIndex].Destroy();
                    s_OnScreenDevices.RemoveAt(deviceInfoIndex);
                }

                return;
            }
            m_InputEventPtr = s_OnScreenDevices[deviceInfoIndex].eventPtr;

            // We have all we need. Permanently add us.
            s_OnScreenDevices[deviceInfoIndex] =
                s_OnScreenDevices[deviceInfoIndex].AddControl(this);
        }
Пример #7
0
    public void Users_CanDetectChangeInBindings()
    {
        var actions = new InputActionMap();
        var action  = actions.AddAction("action", binding: "<Gamepad>/leftTrigger");

        action.Enable();

        var gamepad1 = InputSystem.AddDevice <Gamepad>();
        var user     = InputUser.PerformPairingWithDevice(gamepad1);

        user.AssociateActionsWithUser(actions);

        InputUser?      receivedUser   = null;
        InputUserChange?receivedChange = null;
        InputDevice     receivedDevice = null;

        InputUser.onChange +=
            (u, c, d) =>
        {
            if (c != InputUserChange.ControlsChanged)
            {
                return;
            }

            Assert.That(receivedUser, Is.Null);
            Assert.That(receivedChange, Is.Null);
            Assert.That(receivedDevice, Is.Null);

            receivedUser   = u;
            receivedChange = c;
            receivedDevice = d;
        };

        // Rebind.
        action.ApplyBindingOverride("<Gamepad>/rightTrigger");

        Assert.That(receivedChange, Is.EqualTo(InputUserChange.ControlsChanged));
        Assert.That(receivedUser, Is.EqualTo(user));
        Assert.That(receivedDevice, Is.Null);

        receivedChange = null;
        receivedUser   = null;
        receivedDevice = null;

        // Pair new device.
        var gamepad2 = InputSystem.AddDevice <Gamepad>();

        InputUser.PerformPairingWithDevice(gamepad2, user: user);

        Assert.That(receivedChange, Is.EqualTo(InputUserChange.ControlsChanged));
        Assert.That(receivedUser, Is.EqualTo(user));
        Assert.That(receivedDevice, Is.Null);

        receivedChange = null;
        receivedUser   = null;
        receivedDevice = null;

        // Unpair device.
        user.UnpairDevice(gamepad1);

        Assert.That(receivedChange, Is.EqualTo(InputUserChange.ControlsChanged));
        Assert.That(receivedUser, Is.EqualTo(user));
        Assert.That(receivedDevice, Is.Null);

        receivedChange = null;
        receivedUser   = null;
        receivedDevice = null;

        // Remove user and then add new one.
        var oldUser = user;

        user.UnpairDevicesAndRemoveUser();

        Assert.That(receivedChange, Is.EqualTo(InputUserChange.ControlsChanged));
        Assert.That(receivedUser, Is.EqualTo(oldUser));
        Assert.That(receivedDevice, Is.Null);

        receivedChange = null;
        receivedUser   = null;
        receivedDevice = null;

        user = InputUser.PerformPairingWithDevice(gamepad1);
        user.AssociateActionsWithUser(actions);

        Assert.That(receivedChange, Is.EqualTo(InputUserChange.ControlsChanged));
        Assert.That(receivedUser, Is.EqualTo(user));
        Assert.That(receivedDevice, Is.Null);

        receivedChange = null;
        receivedUser   = null;
        receivedDevice = null;

        action.ApplyBindingOverride("<Gamepad>/leftTrigger");

        Assert.That(receivedChange, Is.EqualTo(InputUserChange.ControlsChanged));
        Assert.That(receivedUser, Is.EqualTo(user));
        Assert.That(receivedDevice, Is.Null);
    }
Пример #8
0
    private void FixedUpdate()
    {
        if (Gamepad.current != null)
        {
            currentGamepad = Gamepad.current;
            if (currentGamepad.selectButton.wasPressedThisFrame)
            {
                m_GameFlowManager.OnJoin();
            }
        }
        var allGamepads = Gamepad.all;

        Debug.Log(allGamepads.Count);



        currentKeyboard             = Keyboard.current;
        InputSystem.onDeviceChange +=
            (device, change) =>
        {
            switch (change)
            {
            case InputDeviceChange.Added:
                // New Device
                if (device != null)
                {
                    Debug.LogWarning("New device added: " + device);
                    InputSystem.AddDevice(device);
                    for (int i = 0; i < Gamepad.all.Count; ++i)
                    {
                        if (device == Gamepad.all.ToArray()[i])
                        {
                            currentGamepad = Gamepad.all.ToArray()[i];
                        }
                    }
                    //If on touchscreen and gamepad is connected
                    //Disable touch controls and use gamepad
                    //Do vice versa
                }

                break;

            case InputDeviceChange.Disconnected:
                // Device got unplugged
                Debug.LogWarning("Device is disconnected: " + device);
                //InputSystem.Dis
                break;

            case InputDeviceChange.Reconnected:
                // Plugged back in
                Debug.LogWarning("Device reconnected: " + device);
                break;

            case InputDeviceChange.Removed:
                // Remove from Input System entirely; by default, devices stay in the system once discovered
                //Debug.LogWarning("Device removed: " + device);
                InputSystem.RemoveDevice(device);

                break;

            default:
                // See InputDeviceChange reference for other event types.
                break;
            }
        };

        if (!m_GameFlowManager)
        {
            m_GameFlowManager = FindObjectOfType <GameFlowManager>();
        }
    }
Пример #9
0
    public void Users_CanBeMonitoredForChanges()
    {
        InputUser.Add(new TestUser()); // Noise.
        InputUser.Add(new TestUser()); // Noise.
        var user = new TestUser();

        IInputUser      receivedUser   = null;
        InputUserChange?receivedChange = null;

        InputUser.onChange +=
            (usr, change) =>
        {
            Assert.That(receivedChange == null);
            receivedUser   = usr;
            receivedChange = change;
        };

        // Added.
        InputUser.Add(user);

        Assert.That(receivedUser, Is.SameAs(user));
        Assert.That(receivedChange, Is.EqualTo(InputUserChange.Added));

        receivedUser   = null;
        receivedChange = null;

        // NameChanged.
        user.SetUserName("NewName");

        Assert.That(receivedUser, Is.SameAs(user));
        Assert.That(receivedChange, Is.EqualTo(InputUserChange.NameChanged));

        receivedUser   = null;
        receivedChange = null;

        // Same name, no notification.
        user.SetUserName("NewName");

        Assert.That(receivedChange, Is.Null);

        // DevicesChanged.
        var device = InputSystem.AddDevice <Gamepad>();

        user.AssignInputDevice(device);

        Assert.That(receivedUser, Is.SameAs(user));
        Assert.That(receivedChange, Is.EqualTo(InputUserChange.DevicesChanged));

        receivedUser   = null;
        receivedChange = null;

        // Same device, no notification.
        user.AssignInputDevice(device);

        Assert.That(receivedChange, Is.Null);

        // DevicesChanges, removed.
        user.ClearAssignedInputDevices();

        Assert.That(receivedUser, Is.SameAs(user));
        Assert.That(receivedChange, Is.EqualTo(InputUserChange.DevicesChanged));

        receivedUser   = null;
        receivedChange = null;

        // ControlSchemeChanged.
        user.AssignControlScheme("gamepad");

        Assert.That(receivedUser, Is.SameAs(user));
        Assert.That(receivedChange, Is.EqualTo(InputUserChange.ControlSchemeChanged));

        receivedUser   = null;
        receivedChange = null;

        // Same control scheme, no notification.
        user.AssignControlScheme("gamepad");

        Assert.That(receivedChange, Is.Null);

        // Removed.
        InputUser.Remove(user);

        Assert.That(receivedUser, Is.SameAs(user));
        Assert.That(receivedChange, Is.EqualTo(InputUserChange.Removed));

        ////TODO: actions
        ////TODO: activate, passivate
    }
Пример #10
0
        private static void OnUpdate(InputUpdateType updateType)
        {
            if (api == null)
            {
                return;
            }

            // Update controller state.
            api.RunFrame();

            // Check if we have any new controllers have appeared.
            if (s_ConnectedControllers == null)
            {
                s_ConnectedControllers = new SteamHandle <SteamController> [STEAM_CONTROLLER_MAX_COUNT];
            }
            var numConnectedControllers = api.GetConnectedControllers(s_ConnectedControllers);

            for (var i = 0; i < numConnectedControllers; ++i)
            {
                var handle = s_ConnectedControllers[i];

                // See if we already have a device for this one.
                if (s_InputDevices != null)
                {
                    SteamController existingDevice = null;
                    for (var n = 0; n < s_InputDeviceCount; ++n)
                    {
                        if (s_InputDevices[n].steamControllerHandle == handle)
                        {
                            existingDevice = s_InputDevices[n];
                            break;
                        }
                    }

                    // Yes, we do.
                    if (existingDevice != null)
                    {
                        continue;
                    }
                }

                ////FIXME: this should not create garbage
                // No, so create a new device.
                var controllerLayouts = InputSystem.ListLayoutsBasedOn("SteamController");
                foreach (var layout in controllerLayouts)
                {
                    // Rather than directly creating a device with the layout, let it go through
                    // the usual matching process.
                    var device = InputSystem.AddDevice(new InputDeviceDescription
                    {
                        interfaceName = SteamController.kSteamInterface,
                        product       = layout
                    });

                    // Make sure it's a SteamController we got.
                    var steamDevice = device as SteamController;
                    if (steamDevice == null)
                    {
                        Debug.LogError(string.Format(
                                           "InputDevice created from layout '{0}' based on the 'SteamController' layout is not a SteamController",
                                           device.layout));
                        continue;
                    }

                    // Resolve the controller's actions.
                    steamDevice.InvokeResolveSteamActions();

                    // Assign it the Steam controller handle.
                    steamDevice.steamControllerHandle = handle;

                    ArrayHelpers.AppendWithCapacity(ref s_InputDevices, ref s_InputDeviceCount, steamDevice);
                }
            }

            // Update all controllers we have.
            for (var i = 0; i < s_InputDeviceCount; ++i)
            {
                var device = s_InputDevices[i];
                var handle = device.steamControllerHandle;

                // Check if the device still exists.
                var stillExists = false;
                for (var n = 0; n < numConnectedControllers; ++n)
                {
                    if (s_ConnectedControllers[n] == handle)
                    {
                        stillExists = true;
                        break;
                    }
                }

                // If not, remove it.
                if (!stillExists)
                {
                    ArrayHelpers.EraseAtByMovingTail(s_InputDevices, ref s_InputDeviceCount, i);
                    ////REVIEW: should this rather queue a device removal event?
                    InputSystem.RemoveDevice(device);
                    --i;
                    continue;
                }

                ////TODO: support polling Steam controllers on an async polling thread adhering to InputSystem.pollingFrequency
                // Otherwise, update it.
                device.InvokeUpdate();
            }
        }
Пример #11
0
            protected override void ContextClickedItem(int id)
            {
                var item = FindItem(id, rootItem);

                if (item == null)
                {
                    return;
                }

                if (item is DeviceItem deviceItem)
                {
                    var menu = new GenericMenu();
                    menu.AddItem(Contents.openDebugView, false, () => InputDeviceDebuggerWindow.CreateOrShowExisting(deviceItem.device));
                    menu.AddItem(Contents.copyDeviceDescription, false,
                                 () => EditorGUIUtility.systemCopyBuffer = deviceItem.device.description.ToJson());
                    menu.AddItem(Contents.removeDevice, false, () => InputSystem.RemoveDevice(deviceItem.device));
                    if (deviceItem.device.enabled)
                    {
                        menu.AddItem(Contents.disableDevice, false, () => InputSystem.DisableDevice(deviceItem.device));
                    }
                    else
                    {
                        menu.AddItem(Contents.enableDevice, false, () => InputSystem.EnableDevice(deviceItem.device));
                    }
                    menu.ShowAsContext();
                }

                if (item is UnsupportedDeviceItem unsupportedDeviceItem)
                {
                    var menu = new GenericMenu();
                    menu.AddItem(Contents.copyDeviceDescription, false,
                                 () => EditorGUIUtility.systemCopyBuffer = unsupportedDeviceItem.description.ToJson());
                    menu.ShowAsContext();
                }

                if (item is LayoutItem layoutItem)
                {
                    var layout = EditorInputControlLayoutCache.TryGetLayout(layoutItem.layoutName);
                    if (layout != null)
                    {
                        var menu = new GenericMenu();
                        menu.AddItem(Contents.copyLayoutAsJSON, false,
                                     () => EditorGUIUtility.systemCopyBuffer = layout.ToJson());
                        if (layout.isDeviceLayout)
                        {
                            menu.AddItem(Contents.createDeviceFromLayout, false,
                                         () => InputSystem.AddDevice(layout.name));
                            menu.AddItem(Contents.generateCodeFromLayout, false, () =>
                            {
                                var fileName   = EditorUtility.SaveFilePanel("Generate InputDevice Code", "", "Fast" + layoutItem.layoutName, "cs");
                                var isInAssets = fileName.StartsWith(Application.dataPath, StringComparison.OrdinalIgnoreCase);
                                if (isInAssets)
                                {
                                    fileName = "Assets/" + fileName.Substring(Application.dataPath.Length + 1);
                                }
                                if (!string.IsNullOrEmpty(fileName))
                                {
                                    var code = InputLayoutCodeGenerator.GenerateCodeFileForDeviceLayout(layoutItem.layoutName, fileName, prefix: "Fast");
                                    File.WriteAllText(fileName, code);
                                    if (isInAssets)
                                    {
                                        AssetDatabase.Refresh();
                                    }
                                }
                            });
                        }
                        menu.ShowAsContext();
                    }
                }
            }
Пример #12
0
    public void Actions_CanPerformPressInteraction()
    {
        var gamepad = InputSystem.AddDevice <Gamepad>();

        // We add a second input device (and bind to it), to test that the binding
        // conflict resolution will not interfere with the interaction handling.
        InputSystem.AddDevice <Keyboard>();

        // Test all three press behaviors concurrently.
        var pressOnlyAction = new InputAction("PressOnly", binding: "<Gamepad>/buttonSouth", interactions: "press");

        pressOnlyAction.AddBinding("<Keyboard>/a");
        var releaseOnlyAction = new InputAction("ReleaseOnly", binding: "<Gamepad>/buttonSouth", interactions: "press(behavior=1)");

        releaseOnlyAction.AddBinding("<Keyboard>/s");
        var pressAndReleaseAction = new InputAction("PressAndRelease", binding: "<Gamepad>/buttonSouth", interactions: "press(behavior=2)");

        pressAndReleaseAction.AddBinding("<Keyboard>/d");

        pressOnlyAction.Enable();
        releaseOnlyAction.Enable();
        pressAndReleaseAction.Enable();

        using (var trace = new InputActionTrace())
        {
            trace.SubscribeToAll();

            runtime.currentTime = 1;
            Press(gamepad.buttonSouth);

            var actions = trace.ToArray();
            Assert.That(actions, Has.Length.EqualTo(5));
            Assert.That(actions,
                        Has.Exactly(1).With.Property("action").SameAs(pressOnlyAction).And.With.Property("phase")
                        .EqualTo(InputActionPhase.Started).And.With.Property("duration")
                        .EqualTo(0));
            Assert.That(actions,
                        Has.Exactly(1).With.Property("action").SameAs(pressOnlyAction).And.With.Property("phase")
                        .EqualTo(InputActionPhase.Performed).And.With.Property("duration")
                        .EqualTo(0));
            Assert.That(actions,
                        Has.Exactly(1).With.Property("action").SameAs(pressAndReleaseAction).And.With.Property("phase")
                        .EqualTo(InputActionPhase.Started).And.With.Property("duration")
                        .EqualTo(0));
            Assert.That(actions,
                        Has.Exactly(1).With.Property("action").SameAs(pressAndReleaseAction).And.With.Property("phase")
                        .EqualTo(InputActionPhase.Performed).And.With.Property("duration")
                        .EqualTo(0));
            Assert.That(actions,
                        Has.Exactly(1).With.Property("action").SameAs(releaseOnlyAction).And.With.Property("phase")
                        .EqualTo(InputActionPhase.Started).And.With.Property("duration")
                        .EqualTo(0));

            trace.Clear();

            runtime.currentTime = 2;
            Release(gamepad.buttonSouth);

            actions = trace.ToArray();
            Assert.That(actions, Has.Length.EqualTo(3));
            Assert.That(actions,
                        Has.Exactly(1).With.Property("action").SameAs(releaseOnlyAction).And.With.Property("phase")
                        .EqualTo(InputActionPhase.Performed).And.With.Property("duration")
                        .EqualTo(1));
            Assert.That(actions,
                        Has.Exactly(1).With.Property("action").SameAs(pressAndReleaseAction).And.With.Property("phase")
                        .EqualTo(InputActionPhase.Started).And.With.Property("duration")
                        .EqualTo(0));
            Assert.That(actions,
                        Has.Exactly(1).With.Property("action").SameAs(pressAndReleaseAction).And.With.Property("phase")
                        .EqualTo(InputActionPhase.Performed).And.With.Property("duration")
                        .EqualTo(0));

            trace.Clear();

            runtime.currentTime = 5;
            Press(gamepad.buttonSouth);

            actions = trace.ToArray();
            Assert.That(actions, Has.Length.EqualTo(5));
            Assert.That(actions,
                        Has.Exactly(1).With.Property("action").SameAs(pressOnlyAction).And.With.Property("phase")
                        .EqualTo(InputActionPhase.Started).And.With.Property("duration")
                        .EqualTo(0));
            Assert.That(actions,
                        Has.Exactly(1).With.Property("action").SameAs(pressOnlyAction).And.With.Property("phase")
                        .EqualTo(InputActionPhase.Performed).And.With.Property("duration")
                        .EqualTo(0));
            Assert.That(actions,
                        Has.Exactly(1).With.Property("action").SameAs(pressAndReleaseAction).And.With.Property("phase")
                        .EqualTo(InputActionPhase.Started).And.With.Property("duration")
                        .EqualTo(0));
            Assert.That(actions,
                        Has.Exactly(1).With.Property("action").SameAs(pressAndReleaseAction).And.With.Property("phase")
                        .EqualTo(InputActionPhase.Performed).And.With.Property("duration")
                        .EqualTo(0));
            Assert.That(actions,
                        Has.Exactly(1).With.Property("action").SameAs(releaseOnlyAction).And.With.Property("phase")
                        .EqualTo(InputActionPhase.Started).And.With.Property("duration")
                        .EqualTo(0));
        }
    }
Пример #13
0
    public void Actions_CanPerformDoubleTapInteraction()
    {
        var gamepad = InputSystem.AddDevice <Gamepad>();

        runtime.advanceTimeEachDynamicUpdate = 0;

        var action = new InputAction(binding: "<Gamepad>/buttonSouth", interactions: "multitap(tapTime=0.5,tapDelay=0.75,tapCount=2)");

        action.Enable();
        using (var trace = new InputActionTrace())
        {
            trace.SubscribeTo(action);

            // Press button.
            runtime.currentTime = 1;
            InputSystem.QueueStateEvent(gamepad, new GamepadState().WithButton(GamepadButton.South), 1);
            InputSystem.Update();

            var actions = trace.ToArray();
            Assert.That(actions, Has.Length.EqualTo(1));
            Assert.That(actions[0].phase, Is.EqualTo(InputActionPhase.Started));
            Assert.That(actions[0].interaction, Is.TypeOf <MultiTapInteraction>());
            Assert.That(actions[0].control, Is.SameAs(gamepad.buttonSouth));
            Assert.That(actions[0].time, Is.EqualTo(1).Within(0.00001));

            trace.Clear();

            // Release before tap time and make sure the double tap cancels.
            runtime.currentTime = 12;
            InputSystem.QueueStateEvent(gamepad, new GamepadState(), 1.75);
            InputSystem.Update();

            actions = trace.ToArray();
            Assert.That(actions, Has.Length.EqualTo(1));
            Assert.That(actions[0].phase, Is.EqualTo(InputActionPhase.Canceled));
            Assert.That(actions[0].interaction, Is.TypeOf <MultiTapInteraction>());
            Assert.That(actions[0].control, Is.SameAs(gamepad.buttonSouth));
            Assert.That(actions[0].time, Is.EqualTo(1.75).Within(0.00001));

            trace.Clear();

            // Press again and then release before tap time. Should see only the start from
            // the initial press.
            runtime.currentTime = 2.5;
            InputSystem.QueueStateEvent(gamepad, new GamepadState().WithButton(GamepadButton.South), 2);
            InputSystem.QueueStateEvent(gamepad, new GamepadState(), 2.25);
            InputSystem.Update();

            actions = trace.ToArray();
            Assert.That(actions, Has.Length.EqualTo(1));
            Assert.That(actions[0].phase, Is.EqualTo(InputActionPhase.Started));
            Assert.That(actions[0].interaction, Is.TypeOf <MultiTapInteraction>());
            Assert.That(actions[0].control, Is.SameAs(gamepad.buttonSouth));
            Assert.That(actions[0].time, Is.EqualTo(2).Within(0.00001));
            Assert.That(actions[0].ReadValue <float>(), Is.EqualTo(1).Within(0.00001));

            trace.Clear();

            // Wait for longer than tapDelay and make sure we're seeing a cancellation.
            runtime.currentTime = 4;
            InputSystem.Update();

            actions = trace.ToArray();
            Assert.That(actions, Has.Length.EqualTo(1));
            Assert.That(actions[0].phase, Is.EqualTo(InputActionPhase.Canceled));
            Assert.That(actions[0].interaction, Is.TypeOf <MultiTapInteraction>());
            Assert.That(actions[0].control, Is.SameAs(gamepad.buttonSouth));
            Assert.That(actions[0].time, Is.EqualTo(4).Within(0.00001));
            Assert.That(actions[0].ReadValue <float>(), Is.EqualTo(0).Within(0.00001));// Button isn't pressed currently.

            trace.Clear();

            // Now press and release within tap time. Then press again within delay time but release
            // only after tap time. Should we started and canceled.
            runtime.currentTime = 6;
            InputSystem.QueueStateEvent(gamepad, new GamepadState().WithButton(GamepadButton.South), 4.7);
            InputSystem.QueueStateEvent(gamepad, new GamepadState(), 4.9);
            InputSystem.QueueStateEvent(gamepad, new GamepadState().WithButton(GamepadButton.South), 5);
            InputSystem.QueueStateEvent(gamepad, new GamepadState(), 5.9);
            InputSystem.Update();

            actions = trace.ToArray();
            Assert.That(actions, Has.Length.EqualTo(2));
            Assert.That(actions[0].phase, Is.EqualTo(InputActionPhase.Started));
            Assert.That(actions[0].interaction, Is.TypeOf <MultiTapInteraction>());
            Assert.That(actions[0].control, Is.SameAs(gamepad.buttonSouth));
            Assert.That(actions[0].time, Is.EqualTo(4.7).Within(0.00001));
            Assert.That(actions[0].ReadValue <float>(), Is.EqualTo(1).Within(0.00001));
            Assert.That(actions[1].phase, Is.EqualTo(InputActionPhase.Canceled));
            Assert.That(actions[1].interaction, Is.TypeOf <MultiTapInteraction>());
            Assert.That(actions[1].control, Is.SameAs(gamepad.buttonSouth));
            Assert.That(actions[1].time, Is.EqualTo(5.9).Within(0.00001));
            Assert.That(actions[1].ReadValue <float>(), Is.EqualTo(0).Within(0.00001));

            trace.Clear();

            // Finally perform a full, proper double tap cycle.
            runtime.currentTime = 8;
            InputSystem.QueueStateEvent(gamepad, new GamepadState().WithButton(GamepadButton.South), 7);
            InputSystem.QueueStateEvent(gamepad, new GamepadState(), 7.25);
            InputSystem.QueueStateEvent(gamepad, new GamepadState().WithButton(GamepadButton.South), 7.5);
            InputSystem.QueueStateEvent(gamepad, new GamepadState(), 7.75);
            InputSystem.Update();

            actions = trace.ToArray();
            Assert.That(actions, Has.Length.EqualTo(2));
            Assert.That(actions[0].phase, Is.EqualTo(InputActionPhase.Started));
            Assert.That(actions[0].interaction, Is.TypeOf <MultiTapInteraction>());
            Assert.That(actions[0].control, Is.SameAs(gamepad.buttonSouth));
            Assert.That(actions[0].time, Is.EqualTo(7).Within(0.00001));
            Assert.That(actions[0].ReadValue <float>(), Is.EqualTo(1).Within(0.00001));
            Assert.That(actions[1].phase, Is.EqualTo(InputActionPhase.Performed));
            Assert.That(actions[1].interaction, Is.TypeOf <MultiTapInteraction>());
            Assert.That(actions[1].control, Is.SameAs(gamepad.buttonSouth));
            Assert.That(actions[1].time, Is.EqualTo(7.75).Within(0.00001));
            Assert.That(actions[1].ReadValue <float>(), Is.Zero.Within(0.00001));
        }
    }
Пример #14
0
    public void Actions_CanPerformHoldInteraction()
    {
        const int timeOffset = 123;

        runtime.currentTimeOffsetToRealtimeSinceStartup = timeOffset;
        runtime.currentTime = 10 + timeOffset;
        var gamepad = InputSystem.AddDevice <Gamepad>();

        var          performedReceivedCalls = 0;
        InputAction  performedAction        = null;
        InputControl performedControl       = null;

        var          startedReceivedCalls = 0;
        InputAction  startedAction        = null;
        InputControl startedControl       = null;

        var          canceledReceivedCalls = 0;
        InputAction  canceledAction        = null;
        InputControl canceledControl       = null;

        var action = new InputAction(binding: "<Gamepad>/{primaryAction}", interactions: "hold(duration=0.4)");

        action.performed +=
            ctx =>
        {
            ++performedReceivedCalls;
            performedAction  = ctx.action;
            performedControl = ctx.control;

            Assert.That(action.phase, Is.EqualTo(InputActionPhase.Performed));
            Assert.That(ctx.duration, Is.GreaterThanOrEqualTo(0.4));
        };
        action.started +=
            ctx =>
        {
            ++startedReceivedCalls;
            startedAction  = ctx.action;
            startedControl = ctx.control;

            Assert.That(action.phase, Is.EqualTo(InputActionPhase.Started));
            Assert.That(ctx.duration, Is.EqualTo(0.0));
        };
        action.canceled +=
            ctx =>
        {
            ++canceledReceivedCalls;
            canceledAction  = ctx.action;
            canceledControl = ctx.control;

            Assert.That(action.phase, Is.EqualTo(InputActionPhase.Canceled));
            Assert.That(ctx.duration, Is.GreaterThan(0.0));
            Assert.That(ctx.duration, Is.LessThan(0.4));
        };
        action.Enable();

        InputSystem.QueueStateEvent(gamepad, new GamepadState().WithButton(GamepadButton.South), 10.0);
        InputSystem.Update();

        Assert.That(startedReceivedCalls, Is.EqualTo(1));
        Assert.That(performedReceivedCalls, Is.Zero);
        Assert.That(canceledReceivedCalls, Is.Zero);
        Assert.That(startedAction, Is.SameAs(action));
        Assert.That(startedControl, Is.SameAs(gamepad.buttonSouth));

        startedReceivedCalls = 0;

        InputSystem.QueueStateEvent(gamepad, new GamepadState(), 10.25);
        InputSystem.Update();

        Assert.That(startedReceivedCalls, Is.Zero);
        Assert.That(performedReceivedCalls, Is.Zero);
        Assert.That(canceledReceivedCalls, Is.EqualTo(1));
        Assert.That(canceledAction, Is.SameAs(action));
        Assert.That(canceledControl, Is.SameAs(gamepad.buttonSouth));
        Assert.That(action.phase, Is.EqualTo(InputActionPhase.Waiting));

        canceledReceivedCalls = 0;

        InputSystem.QueueStateEvent(gamepad, new GamepadState().WithButton(GamepadButton.South), 10.5);
        InputSystem.Update();

        Assert.That(startedReceivedCalls, Is.EqualTo(1));
        Assert.That(performedReceivedCalls, Is.Zero);
        Assert.That(canceledReceivedCalls, Is.Zero);
        Assert.That(startedAction, Is.SameAs(action));
        Assert.That(startedControl, Is.SameAs(gamepad.buttonSouth));
        Assert.That(action.phase, Is.EqualTo(InputActionPhase.Started));

        startedReceivedCalls = 0;

        runtime.currentTime = 10.75 + timeOffset;
        InputSystem.Update();

        Assert.That(startedReceivedCalls, Is.Zero);
        Assert.That(performedReceivedCalls, Is.Zero);
        Assert.That(canceledReceivedCalls, Is.Zero);
        Assert.That(startedAction, Is.SameAs(action));
        Assert.That(startedControl, Is.SameAs(gamepad.buttonSouth));
        Assert.That(action.phase, Is.EqualTo(InputActionPhase.Started));

        runtime.currentTime = 11 + timeOffset;
        InputSystem.Update();

        Assert.That(startedReceivedCalls, Is.Zero);
        Assert.That(performedReceivedCalls, Is.EqualTo(1));
        Assert.That(canceledReceivedCalls, Is.Zero);
        Assert.That(performedAction, Is.SameAs(action));
        Assert.That(performedControl, Is.SameAs(gamepad.buttonSouth));
        Assert.That(action.phase, Is.EqualTo(InputActionPhase.Waiting));
    }
Пример #15
0
    public void Devices_SupportsDualShockOnPS4()
    {
        var device = InputSystem.AddDevice(new InputDeviceDescription
        {
            deviceClass   = "PS4DualShockGamepad", ////REVIEW: this should be the product name instead
            interfaceName = "PS4"
        });

        Assert.That(device, Is.AssignableTo <DualShockGamepad>());
        var gamepad = (DualShockGamepad)device;

        InputSystem.QueueStateEvent(gamepad,
                                    new DualShockGamepadStatePS4
        {
            buttons         = 0xffffffff,
            leftStick       = new Vector2(0.123f, 0.456f),
            rightStick      = new Vector2(0.789f, 0.234f),
            leftTrigger     = 0.567f,
            rightTrigger    = 0.891f,
            acceleration    = new Vector3(0.987f, 0.654f, 0.321f),
            orientation     = new Quaternion(0.111f, 0.222f, 0.333f, 0.444f),
            angularVelocity = new Vector3(0.444f, 0.555f, 0.666f),
            touch0          = new PS4Touch
            {
                touchId  = 123,
                position = new Vector2(0.231f, 0.342f)
            },
            touch1 = new PS4Touch
            {
                touchId  = 456,
                position = new Vector2(0.453f, 0.564f)
            },
        });
        InputSystem.Update();

        Assert.That(gamepad.squareButton.isPressed);
        Assert.That(gamepad.triangleButton.isPressed);
        Assert.That(gamepad.circleButton.isPressed);
        Assert.That(gamepad.crossButton.isPressed);
        Assert.That(gamepad.buttonSouth.isPressed);
        Assert.That(gamepad.buttonNorth.isPressed);
        Assert.That(gamepad.buttonEast.isPressed);
        Assert.That(gamepad.buttonWest.isPressed);
        Assert.That(gamepad.leftStickButton.isPressed);
        Assert.That(gamepad.rightStickButton.isPressed);
        Assert.That(gamepad.L3.isPressed);
        Assert.That(gamepad.R3.isPressed);

        Assert.That(gamepad.leftStick.x.ReadValue(), Is.EqualTo(0.123).Within(0.00001));
        Assert.That(gamepad.leftStick.y.ReadValue(), Is.EqualTo(0.456).Within(0.00001));
        Assert.That(gamepad.rightStick.x.ReadValue(), Is.EqualTo(0.789).Within(0.00001));
        Assert.That(gamepad.rightStick.y.ReadValue(), Is.EqualTo(0.234).Within(0.00001));
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.567).Within(0.00001));
        Assert.That(gamepad.rightTrigger.ReadValue(), Is.EqualTo(0.891).Within(0.00001));

        Assert.That(gamepad.acceleration.x.ReadValue(), Is.EqualTo(0.987).Within(0.00001));
        Assert.That(gamepad.acceleration.y.ReadValue(), Is.EqualTo(0.654).Within(0.00001));
        Assert.That(gamepad.acceleration.z.ReadValue(), Is.EqualTo(0.321).Within(0.00001));

        Quaternion orientation = gamepad.orientation.ReadValue();

        Assert.That(orientation.x, Is.EqualTo(0.111).Within(0.00001));
        Assert.That(orientation.y, Is.EqualTo(0.222).Within(0.00001));
        Assert.That(orientation.z, Is.EqualTo(0.333).Within(0.00001));
        Assert.That(orientation.w, Is.EqualTo(0.444).Within(0.00001));

        Assert.That(gamepad.angularVelocity.x.ReadValue(), Is.EqualTo(0.444).Within(0.00001));
        Assert.That(gamepad.angularVelocity.y.ReadValue(), Is.EqualTo(0.555).Within(0.00001));
        Assert.That(gamepad.angularVelocity.z.ReadValue(), Is.EqualTo(0.666).Within(0.00001));

        ////TODO: touch
    }
Пример #16
0
    public void Controls_CanKeepListsOfControls_WithoutAllocatingGCMemory()
    {
        InputSystem.AddDevice <Mouse>(); // Noise.
        var gamepad  = InputSystem.AddDevice <Gamepad>();
        var keyboard = InputSystem.AddDevice <Keyboard>();

        var list = default(InputControlList <InputControl>);

        Assert.That(() => { list = new InputControlList <InputControl>(); }, Is.Not.AllocatingGCMemory());

        try
        {
            Assert.That(list.Count, Is.Zero);
            Assert.That(list.ToArray(), Is.Empty);
            Assert.That(() => list[0], Throws.TypeOf <ArgumentOutOfRangeException>());

            list.Capacity = 4;

            Assert.That(() =>
            {
                list.Add(gamepad.leftStick);
                list.Add(null); // Permissible to add null entry.
                list.Add(keyboard.spaceKey);
                list.Add(keyboard);
            }, Is.Not.AllocatingGCMemory());

            Assert.That(list.Count, Is.EqualTo(4));
            Assert.That(list.Capacity, Is.EqualTo(4));
            Assert.That(list[0], Is.SameAs(gamepad.leftStick));
            Assert.That(list[1], Is.Null);
            Assert.That(list[2], Is.SameAs(keyboard.spaceKey));
            Assert.That(list[3], Is.SameAs(keyboard));
            Assert.That(() => list[4], Throws.TypeOf <ArgumentOutOfRangeException>());
            Assert.That(list.ToArray(),
                        Is.EquivalentTo(new InputControl[] { gamepad.leftStick, null, keyboard.spaceKey, keyboard }));
            Assert.That(list.Contains(gamepad.leftStick));
            Assert.That(list.Contains(null));
            Assert.That(list.Contains(keyboard.spaceKey));
            Assert.That(list.Contains(keyboard));

            Assert.That(() =>
            {
                list.RemoveAt(1);
                list.Remove(keyboard);
            }, Is.Not.AllocatingGCMemory());

            Assert.That(list.Count, Is.EqualTo(2));
            Assert.That(list.Capacity, Is.EqualTo(4));
            Assert.That(list[0], Is.SameAs(gamepad.leftStick));
            Assert.That(list[1], Is.SameAs(keyboard.spaceKey));
            Assert.That(() => list[2], Throws.TypeOf <ArgumentOutOfRangeException>());
            Assert.That(list.ToArray(), Is.EquivalentTo(new InputControl[] { gamepad.leftStick, keyboard.spaceKey }));
            Assert.That(list.Contains(gamepad.leftStick));
            Assert.That(!list.Contains(null));
            Assert.That(list.Contains(keyboard.spaceKey));
            Assert.That(!list.Contains(keyboard));

            list.AddRange(new InputControl[] { keyboard.aKey, keyboard.bKey }, count: 1, destinationIndex: 0);

            Assert.That(list.Count, Is.EqualTo(3));
            Assert.That(list.Capacity, Is.EqualTo(4));
            Assert.That(list,
                        Is.EquivalentTo(new InputControl[]
                                        { keyboard.aKey, gamepad.leftStick, keyboard.spaceKey }));

            list.AddRange(new InputControl[] { keyboard.bKey, keyboard.cKey });

            Assert.That(list.Count, Is.EqualTo(5));
            Assert.That(list.Capacity, Is.EqualTo(10));
            Assert.That(list,
                        Is.EquivalentTo(new InputControl[]
                                        { keyboard.aKey, gamepad.leftStick, keyboard.spaceKey, keyboard.bKey, keyboard.cKey }));

            using (var toAdd = new InputControlList <InputControl>(gamepad.buttonNorth, gamepad.buttonEast, gamepad.buttonWest))
                list.AddSlice(toAdd, count: 1, destinationIndex: 1, sourceIndex: 2);

            Assert.That(list.Count, Is.EqualTo(6));
            Assert.That(list.Capacity, Is.EqualTo(10));
            Assert.That(list,
                        Is.EquivalentTo(new InputControl[]
                                        { keyboard.aKey, gamepad.buttonWest, gamepad.leftStick, keyboard.spaceKey, keyboard.bKey, keyboard.cKey }));

            list[0] = keyboard.zKey;

            Assert.That(list,
                        Is.EquivalentTo(new InputControl[]
                                        { keyboard.zKey, gamepad.buttonWest, gamepad.leftStick, keyboard.spaceKey, keyboard.bKey, keyboard.cKey }));

            list.Clear();

            Assert.That(list.Count, Is.Zero);
            Assert.That(list.Capacity, Is.EqualTo(10));
            Assert.That(list.ToArray(), Is.Empty);
            Assert.That(() => list[0], Throws.TypeOf <ArgumentOutOfRangeException>());
            Assert.That(!list.Contains(gamepad.leftStick));
            Assert.That(!list.Contains(null));
            Assert.That(!list.Contains(keyboard.spaceKey));
            Assert.That(!list.Contains(keyboard));
        }
        finally
        {
            list.Dispose();
        }
    }
Пример #17
0
    public void Devices_SupportsAndroidGamepad()
    {
        var device = InputSystem.AddDevice(new InputDeviceDescription
        {
            interfaceName = "Android",
            deviceClass   = "AndroidGameController",
            capabilities  = new AndroidDeviceCapabilities
            {
                inputSources = AndroidInputSource.Gamepad | AndroidInputSource.Joystick,
            }.ToJson()
        });

        Assert.That(device, Is.TypeOf <AndroidGamepad>());
        var controller = (AndroidGamepad)device;

        var leftStick  = new Vector2(0.789f, 0.987f);
        var rightStick = new Vector2(0.654f, 0.321f);

        // Note: Regarding triggers, android sends different events depending to which device the controller is connected.
        //       For ex., when NVIDIA shield controller when connected to Shield Console, triggers generate events:
        //            Left Trigger -> AndroidAxis.Brake, AndroidAxis.LtTrigger
        //            Right Trigger -> AndroidAxis.Gas, AndroidAxis.RtTrigger
        //       BUT
        //           when NVIDIA shield controller when connected to Samsung phone, triggers generate events:
        //            Left Trigger -> AndroidAxis.Brake
        //            Right Trigger -> AndroidAxis.Gas
        //
        //       This is why we're only reading and validating that events are correctly processed from AndroidAxis.Brake & AndroidAxis.Gas
        InputSystem.QueueStateEvent(controller,
                                    new AndroidGameControllerState()
                                    .WithAxis(AndroidAxis.Brake, 0.123f)
                                    .WithAxis(AndroidAxis.Gas, 0.456f)
                                    .WithAxis(AndroidAxis.X, leftStick.x)
                                    .WithAxis(AndroidAxis.Y, leftStick.y)
                                    .WithAxis(AndroidAxis.Z, rightStick.x)
                                    .WithAxis(AndroidAxis.Rz, rightStick.y));

        InputSystem.Update();

        var leftStickDeadzone  = controller.leftStick.TryGetProcessor <StickDeadzoneProcessor>();
        var rightStickDeadzone = controller.leftStick.TryGetProcessor <StickDeadzoneProcessor>();

        // Y is upside down on Android.
        Assert.That(controller.leftStick.ReadValue(), Is.EqualTo(leftStickDeadzone.Process(new Vector2(leftStick.x, -leftStick.y))));
        Assert.That(controller.rightStick.ReadValue(), Is.EqualTo(rightStickDeadzone.Process(new Vector2(rightStick.x, -rightStick.y))));

        Assert.That(controller.leftStick.left.ReadValue(), Is.EqualTo(0.0f));
        Assert.That(controller.leftStick.right.ReadValue(), Is.EqualTo(new AxisDeadzoneProcessor().Process(leftStick.x)));
        Assert.That(controller.leftStick.up.ReadValue(), Is.EqualTo(0.0f));
        Assert.That(controller.leftStick.down.ReadValue(), Is.EqualTo(new AxisDeadzoneProcessor().Process(leftStick.y)));

        Assert.That(controller.rightStick.left.ReadValue(), Is.EqualTo(0.0f));
        Assert.That(controller.rightStick.right.ReadValue(), Is.EqualTo(new AxisDeadzoneProcessor().Process(rightStick.x)));
        Assert.That(controller.rightStick.up.ReadValue(), Is.EqualTo(0.0f));
        Assert.That(controller.rightStick.down.ReadValue(), Is.EqualTo(new AxisDeadzoneProcessor().Process(rightStick.y)));

        Assert.That(controller.leftTrigger.ReadValue(), Is.EqualTo(0.123).Within(0.000001));
        Assert.That(controller.rightTrigger.ReadValue(), Is.EqualTo(0.456).Within(0.000001));

        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonA), controller.buttonSouth);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonX), controller.buttonWest);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonY), controller.buttonNorth);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonB), controller.buttonEast);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonThumbl), controller.leftStickButton);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonThumbr), controller.rightStickButton);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonL1), controller.leftShoulder);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonR1), controller.rightShoulder);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonStart), controller.startButton);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonSelect), controller.selectButton);

        // Move sticks to opposite directions
        InputSystem.QueueStateEvent(controller,
                                    new AndroidGameControllerState()
                                    .WithAxis(AndroidAxis.X, -leftStick.x)
                                    .WithAxis(AndroidAxis.Y, -leftStick.y)
                                    .WithAxis(AndroidAxis.Z, -rightStick.x)
                                    .WithAxis(AndroidAxis.Rz, -rightStick.y));

        InputSystem.Update();

        Assert.That(controller.leftStick.left.ReadValue(), Is.EqualTo(new AxisDeadzoneProcessor().Process(leftStick.x)));
        Assert.That(controller.leftStick.right.ReadValue(), Is.EqualTo(0.0f));
        Assert.That(controller.leftStick.up.ReadValue(), Is.EqualTo(new AxisDeadzoneProcessor().Process(leftStick.y)));
        Assert.That(controller.leftStick.down.ReadValue(), Is.EqualTo(0.0f));

        Assert.That(controller.rightStick.left.ReadValue(), Is.EqualTo(new AxisDeadzoneProcessor().Process(rightStick.x)));
        Assert.That(controller.rightStick.right.ReadValue(), Is.EqualTo(0.0f));
        Assert.That(controller.rightStick.up.ReadValue(), Is.EqualTo(new AxisDeadzoneProcessor().Process(rightStick.y)));
        Assert.That(controller.rightStick.down.ReadValue(), Is.EqualTo(0.0f));
    }
    public void Controls_DpadVectorsAreCircular()
    {
        var gamepad = InputSystem.AddDevice <Gamepad>();

        // Up.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            buttons = 1 << (int)GamepadState.Button.DpadUp
        });
        InputSystem.Update();

        Assert.That(gamepad.dpad.ReadValue(), Is.EqualTo(Vector2.up));

        // Up left.
        InputSystem.QueueStateEvent(gamepad,
                                    new GamepadState
        {
            buttons = 1 << (int)GamepadState.Button.DpadUp | 1 << (int)GamepadState.Button.DpadLeft
        });
        InputSystem.Update();

        Assert.That(gamepad.dpad.ReadValue().x, Is.EqualTo((Vector2.up + Vector2.left).normalized.x).Within(0.00001));
        Assert.That(gamepad.dpad.ReadValue().y, Is.EqualTo((Vector2.up + Vector2.left).normalized.y).Within(0.00001));

        // Left.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            buttons = 1 << (int)GamepadState.Button.DpadLeft
        });
        InputSystem.Update();

        Assert.That(gamepad.dpad.ReadValue(), Is.EqualTo(Vector2.left));

        // Down left.
        InputSystem.QueueStateEvent(gamepad,
                                    new GamepadState
        {
            buttons = 1 << (int)GamepadState.Button.DpadDown | 1 << (int)GamepadState.Button.DpadLeft
        });
        InputSystem.Update();

        Assert.That(gamepad.dpad.ReadValue().x, Is.EqualTo((Vector2.down + Vector2.left).normalized.x).Within(0.00001));
        Assert.That(gamepad.dpad.ReadValue().y, Is.EqualTo((Vector2.down + Vector2.left).normalized.y).Within(0.00001));

        // Down.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            buttons = 1 << (int)GamepadState.Button.DpadDown
        });
        InputSystem.Update();

        Assert.That(gamepad.dpad.ReadValue(), Is.EqualTo(Vector2.down));

        // Down right.
        InputSystem.QueueStateEvent(gamepad,
                                    new GamepadState
        {
            buttons = 1 << (int)GamepadState.Button.DpadDown | 1 << (int)GamepadState.Button.DpadRight
        });
        InputSystem.Update();

        Assert.That(gamepad.dpad.ReadValue().x,
                    Is.EqualTo((Vector2.down + Vector2.right).normalized.x).Within(0.00001));
        Assert.That(gamepad.dpad.ReadValue().y,
                    Is.EqualTo((Vector2.down + Vector2.right).normalized.y).Within(0.00001));

        // Right.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            buttons = 1 << (int)GamepadState.Button.DpadRight
        });
        InputSystem.Update();

        Assert.That(gamepad.dpad.ReadValue(), Is.EqualTo(Vector2.right));

        // Up right.
        InputSystem.QueueStateEvent(gamepad,
                                    new GamepadState
        {
            buttons = 1 << (int)GamepadState.Button.DpadUp | 1 << (int)GamepadState.Button.DpadRight
        });
        InputSystem.Update();

        Assert.That(gamepad.dpad.ReadValue().x, Is.EqualTo((Vector2.up + Vector2.right).normalized.x).Within(0.00001));
        Assert.That(gamepad.dpad.ReadValue().y, Is.EqualTo((Vector2.up + Vector2.right).normalized.y).Within(0.00001));
    }
Пример #19
0
 private void Start()
 {
     keyboard = InputSystem.AddDevice <Keyboard>();
 }
Пример #20
0
    public void Components_CanUpdateGameObjectTransformThroughTrackedPoseDriver()
    {
        var testpos = new Vector3(1.0f, 2.0f, 3.0f);
        var testrot = new Quaternion(0.09853293f, 0.09853293f, 0.09853293f, 0.9853293f);

        var go     = new GameObject();
        var tpd1   = go.AddComponent <TrackedPoseDriver>();
        var tpd    = tpd1;
        var device = InputSystem.AddDevice <TestHMD>();

        InputEventPtr stateEvent;

        using (StateEvent.From(device, out stateEvent))
        {
            var positionAction = new InputAction();
            positionAction.AddBinding("<TestHMD>/vector3");

            var rotationAction = new InputAction();
            rotationAction.AddBinding("<TestHMD>/quaternion");

            tpd.positionAction = positionAction;
            tpd.rotationAction = rotationAction;

            // before render only
            var go1 = tpd.gameObject;
            go1.transform.position = Vector3.zero;
            go1.transform.rotation = new Quaternion(0, 0, 0, 0);
            tpd.updateType         = TrackedPoseDriver.UpdateType.BeforeRender;
            tpd.trackingType       = TrackedPoseDriver.TrackingType.RotationAndPosition;

            device.quaternion.WriteValueIntoEvent(testrot, stateEvent);
            device.vector3.WriteValueIntoEvent(testpos, stateEvent);

            InputSystem.QueueEvent(stateEvent);
            InputSystem.Update(InputUpdateType.Dynamic);
            Assert.That(tpd.gameObject.transform.position, Is.Not.EqualTo(testpos));
            Assert.That(!tpd.gameObject.transform.rotation.Equals(testrot));

            var go2 = tpd.gameObject;
            go2.transform.position = Vector3.zero;
            go2.transform.rotation = new Quaternion(0, 0, 0, 0);
            InputSystem.QueueEvent(stateEvent);
            InputSystem.Update(InputUpdateType.BeforeRender);
            Assert.That(tpd.gameObject.transform.position, Is.EqualTo(testpos));
            Assert.That(tpd.gameObject.transform.rotation.Equals(testrot));

            // update only
            var go3 = tpd.gameObject;
            go3.transform.position = Vector3.zero;
            go3.transform.rotation = new Quaternion(0, 0, 0, 0);
            tpd.updateType         = TrackedPoseDriver.UpdateType.Update;
            tpd.trackingType       = TrackedPoseDriver.TrackingType.RotationAndPosition;

            InputSystem.QueueEvent(stateEvent);
            InputSystem.Update(InputUpdateType.Dynamic);
            Assert.That(tpd.gameObject.transform.position, Is.EqualTo(testpos));
            Assert.That(tpd.gameObject.transform.rotation.Equals(testrot));

            GameObject go4 = tpd.gameObject;
            go4.transform.position = Vector3.zero;
            go4.transform.rotation = new Quaternion(0, 0, 0, 0);
            InputSystem.QueueEvent(stateEvent);
            InputSystem.Update(InputUpdateType.BeforeRender);
            Assert.That(tpd.gameObject.transform.position, Is.Not.EqualTo(testpos));
            Assert.That(!tpd.gameObject.transform.rotation.Equals(testrot));


            // check the rot/pos case also Update AND Render.
            tpd.updateType   = TrackedPoseDriver.UpdateType.UpdateAndBeforeRender;
            tpd.trackingType = TrackedPoseDriver.TrackingType.PositionOnly;
            var go5 = tpd.gameObject;
            go5.transform.position = Vector3.zero;
            go5.transform.rotation = new Quaternion(0, 0, 0, 0);

            InputSystem.QueueEvent(stateEvent);
            InputSystem.Update(InputUpdateType.Dynamic);
            Assert.That(tpd.gameObject.transform.position, Is.EqualTo(testpos));
            Assert.That(!tpd.gameObject.transform.rotation.Equals(testrot));

            tpd.trackingType = TrackedPoseDriver.TrackingType.RotationOnly;
            var go6 = tpd.gameObject;
            go6.transform.position = Vector3.zero;
            go6.transform.rotation = new Quaternion(0, 0, 0, 0);
            InputSystem.QueueEvent(stateEvent);
            InputSystem.Update(InputUpdateType.BeforeRender);
            Assert.That(tpd.gameObject.transform.position, Is.Not.EqualTo(testpos));
            Assert.That(tpd.gameObject.transform.rotation.Equals(testrot));
        }
    }
Пример #21
0
    public void Users_CanDetectUseOfUnpairedDevice()
    {
        // Instead of adding a standard Gamepad, add a custom one that has a noisy gyro
        // control added to it so that we can test whether the system can differentiate the
        // noise of the gyro from real user input.
        const string gamepadWithNoisyGyro = @"
            {
                ""name"" : ""GamepadWithNoisyGyro"",
                ""extend"" : ""Gamepad"",
                ""controls"" : [
                    { ""name"" : ""gyro"", ""layout"" : ""Quaternion"", ""noisy"" : true }
                ]
            }
        ";

        ++InputUser.listenForUnpairedDeviceActivity;

        var receivedControls = new List <InputControl>();

        InputUser.onUnpairedDeviceUsed +=
            (control, eventPtr) => { receivedControls.Add(control); };

        InputSystem.RegisterLayout(gamepadWithNoisyGyro);
        var gamepad = (Gamepad)InputSystem.AddDevice("GamepadWithNoisyGyro");

        // First send some noise on the gyro.
        Set((QuaternionControl)gamepad["gyro"], new Quaternion(1, 2, 3, 4));

        Assert.That(receivedControls, Is.Empty);

        // Now send some real interaction.
        PressAndRelease(gamepad.buttonSouth);

        Assert.That(receivedControls, Is.EquivalentTo(new[] { gamepad.aButton }));

        receivedControls.Clear();

        // Now pair the device to a user and try the same thing again.
        var user = InputUser.PerformPairingWithDevice(gamepad);

        PressAndRelease(gamepad.buttonEast);

        Assert.That(receivedControls, Is.Empty);

        receivedControls.Clear();

        // Unpair the device and turn off the feature to make sure we're not getting a notification.
        user.UnpairDevice(gamepad);
        --InputUser.listenForUnpairedDeviceActivity;

        PressAndRelease(gamepad.buttonSouth);

        Assert.That(receivedControls, Is.Empty);

        // Turn it back on and actuate two controls on the gamepad. Make sure we get *both* actuations.
        // NOTE: This is important for when use of an unpaired device only does something when certain
        //       controls are used but doesn't do anything if others are used. For example, if the use
        //       of unpaired devices is driving player joining logic but only button presses lead to joins,
        //       then if we were to only send the first actuation we come across, it may be for an
        //       irrelevant control (e.g. sticks on gamepad).

        ++InputUser.listenForUnpairedDeviceActivity;

        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftStick = new Vector2(1, 0)
        }.WithButton(GamepadButton.A));
        InputSystem.Update();

        Assert.That(receivedControls, Has.Count.EqualTo(2));
        Assert.That(receivedControls, Has.Exactly(1).SameAs(gamepad.leftStick.x));
        Assert.That(receivedControls, Has.Exactly(1).SameAs(gamepad.aButton));
    }
Пример #22
0
    public void Devices_SupportXboxWirelessControllerOnOSX()
    {
        var device = InputSystem.AddDevice(new InputDeviceDescription
        {
            interfaceName = "HID",
            product       = "Xbox One Wireless Controller",
            manufacturer  = "Microsoft"
        });

        Assert.That(device, Is.AssignableTo <XInputController>());
        Assert.That(device, Is.AssignableTo <XboxOneGampadMacOSWireless>());
        var gamepad = (XboxOneGampadMacOSWireless)device;

        InputSystem.QueueStateEvent(gamepad,
                                    new XInputControllerWirelessOSXState
        {
            leftStickX   = 65535,
            leftStickY   = 0,
            rightStickX  = 65535,
            rightStickY  = 0,
            leftTrigger  = 1023,
            rightTrigger = 1023,
        });

        InputSystem.Update();

        Assert.That(gamepad.leftStick.x.ReadValue(), Is.EqualTo(0.9999).Within(0.001));
        Assert.That(gamepad.leftStick.y.ReadValue(), Is.EqualTo(0.9999).Within(0.001));
        Assert.That(gamepad.leftStick.up.ReadValue(), Is.EqualTo(0.9999).Within(0.001));
        Assert.That(gamepad.leftStick.down.ReadValue(), Is.EqualTo(0.0).Within(0.001));
        Assert.That(gamepad.leftStick.right.ReadValue(), Is.EqualTo(0.9999).Within(0.001));
        Assert.That(gamepad.leftStick.left.ReadValue(), Is.EqualTo(0.0).Within(0.001));

        Assert.That(gamepad.rightStick.x.ReadValue(), Is.EqualTo(0.9999).Within(0.001));
        Assert.That(gamepad.rightStick.y.ReadValue(), Is.EqualTo(0.9999).Within(0.001));
        Assert.That(gamepad.rightStick.up.ReadValue(), Is.EqualTo(0.9999).Within(0.001));
        Assert.That(gamepad.rightStick.down.ReadValue(), Is.EqualTo(0.0).Within(0.001));
        Assert.That(gamepad.rightStick.right.ReadValue(), Is.EqualTo(0.9999).Within(0.001));
        Assert.That(gamepad.rightStick.left.ReadValue(), Is.EqualTo(0.0).Within(0.001));

        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(1));
        Assert.That(gamepad.rightTrigger.ReadValue(), Is.EqualTo(1));

        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithButton(XInputControllerWirelessOSXState.Button.A), gamepad.aButton);
        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithButton(XInputControllerWirelessOSXState.Button.A), gamepad.buttonSouth);
        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithButton(XInputControllerWirelessOSXState.Button.B), gamepad.bButton);
        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithButton(XInputControllerWirelessOSXState.Button.B), gamepad.buttonEast);
        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithButton(XInputControllerWirelessOSXState.Button.X), gamepad.xButton);
        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithButton(XInputControllerWirelessOSXState.Button.X), gamepad.buttonWest);
        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithButton(XInputControllerWirelessOSXState.Button.Y), gamepad.yButton);
        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithButton(XInputControllerWirelessOSXState.Button.Y), gamepad.buttonNorth);

        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithDpad(5), gamepad.dpad.down);
        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithDpad(1), gamepad.dpad.up);
        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithDpad(7), gamepad.dpad.left);
        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithDpad(3), gamepad.dpad.right);

        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithButton(XInputControllerWirelessOSXState.Button.LeftThumbstickPress), gamepad.leftStickButton);
        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithButton(XInputControllerWirelessOSXState.Button.RightThumbstickPress), gamepad.rightStickButton);

        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithButton(XInputControllerWirelessOSXState.Button.LeftShoulder), gamepad.leftShoulder);
        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithButton(XInputControllerWirelessOSXState.Button.RightShoulder), gamepad.rightShoulder);

        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithButton(XInputControllerWirelessOSXState.Button.Start), gamepad.menu);
        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithButton(XInputControllerWirelessOSXState.Button.Start), gamepad.startButton);
        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithButton(XInputControllerWirelessOSXState.Button.Select), gamepad.view);
        AssertButtonPress(gamepad, XInputControllerWirelessOSXState.defaultState.WithButton(XInputControllerWirelessOSXState.Button.Select), gamepad.selectButton);

        // Test to make sure that the default state is not set to input values of 0, but to the center of the sticks
        InputSystem.QueueStateEvent(gamepad,
                                    new XInputControllerWirelessOSXState
        {
            leftStickX   = 0,
            leftStickY   = 0,
            rightStickX  = 0,
            rightStickY  = 0,
            leftTrigger  = 0,
            rightTrigger = 0,
        });
        InputSystem.Update();
        Assert.That(gamepad.leftStick.IsActuated());
        Assert.That(gamepad.leftStick.x.IsActuated());
        Assert.That(gamepad.leftStick.CheckStateIsAtDefault(), Is.False);
        Assert.That(gamepad.leftStick.x.CheckStateIsAtDefault(), Is.False);
        Assert.That(gamepad.leftTrigger.IsActuated(), Is.False);
        Assert.That(gamepad.leftTrigger.CheckStateIsAtDefault());
    }
Пример #23
0
    public unsafe void Events_AreTimeslicedByDefault()
    {
        InputSystem.settings.updateMode = InputSettings.UpdateMode.ProcessEventsInFixedUpdate;

        runtime.currentTimeForFixedUpdate = 1;

        var gamepad = InputSystem.AddDevice <Gamepad>();

        var receivedEvents = new List <InputEvent>();

        InputSystem.onEvent +=
            (eventPtr, _) => receivedEvents.Add(*eventPtr.data);

        // First fixed update should just take everything.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.1234f
        }, 1);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.2345f
        }, 2);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.3456f
        }, 2.9);

        runtime.currentTimeForFixedUpdate = 3;

        InputSystem.Update(InputUpdateType.Fixed);

        Assert.That(receivedEvents, Has.Count.EqualTo(3));
        Assert.That(receivedEvents[0].time, Is.EqualTo(1).Within(0.00001));
        Assert.That(receivedEvents[1].time, Is.EqualTo(2).Within(0.00001));
        Assert.That(receivedEvents[2].time, Is.EqualTo(2.9).Within(0.00001));
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.3456).Within(0.00001));

        Assert.That(InputUpdate.s_LastUpdateRetainedEventCount, Is.Zero);

        receivedEvents.Clear();

        runtime.currentTimeForFixedUpdate += 1 / 60.0f;

        // From now on, fixed updates should only take what falls in their slice.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.1234f
        }, 3 + 0.001);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.2345f
        }, 3 + 0.002);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.3456f
        }, 3 + 1.0 / 60 + 0.001);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.4567f
        }, 3 + 2 * (1.0 / 60) + 0.001);

        InputSystem.Update(InputUpdateType.Fixed);

        Assert.That(receivedEvents, Has.Count.EqualTo(2));
        Assert.That(receivedEvents[0].time, Is.EqualTo(3 + 0.001).Within(0.00001));
        Assert.That(receivedEvents[1].time, Is.EqualTo(3 + 0.002).Within(0.00001));
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.2345).Within(0.00001));

        Assert.That(InputUpdate.s_LastUpdateRetainedEventCount, Is.EqualTo(2));

        receivedEvents.Clear();

        runtime.currentTimeForFixedUpdate += 1 / 60.0f;

        InputSystem.Update(InputUpdateType.Fixed);

        Assert.That(receivedEvents, Has.Count.EqualTo(1));
        Assert.That(receivedEvents[0].time, Is.EqualTo(3 + 1.0 / 60 + 0.001).Within(0.00001));
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.3456).Within(0.00001));

        Assert.That(InputUpdate.s_LastUpdateRetainedEventCount, Is.EqualTo(1));

        receivedEvents.Clear();

        runtime.currentTimeForFixedUpdate += 1 / 60.0f;

        InputSystem.Update(InputUpdateType.Fixed);

        Assert.That(receivedEvents, Has.Count.EqualTo(1));
        Assert.That(receivedEvents[0].time, Is.EqualTo(3 + 2 * (1.0 / 60) + 0.001).Within(0.00001));
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.4567).Within(0.00001));

        Assert.That(InputUpdate.s_LastUpdateRetainedEventCount, Is.Zero);

        receivedEvents.Clear();

        runtime.currentTimeForFixedUpdate += 1 / 60.0f;

        InputSystem.Update(InputUpdateType.Fixed);

        Assert.That(receivedEvents, Has.Count.Zero);
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.4567).Within(0.00001));

        Assert.That(InputUpdate.s_LastUpdateRetainedEventCount, Is.Zero);
    }
Пример #24
0
    public void Devices_SupportXboxControllerOnOSX()
    {
        var device = InputSystem.AddDevice(new InputDeviceDescription
        {
            interfaceName = "HID",
            product       = "Xbox One Wired Controller",
            manufacturer  = "Microsoft"
        });

        Assert.That(device, Is.AssignableTo <XInputController>());
        Assert.That(device, Is.AssignableTo <XboxGamepadMacOS>());
        var gamepad = (XboxGamepadMacOS)device;

        InputSystem.QueueStateEvent(gamepad,
                                    new XInputControllerOSXState
        {
            leftStickX   = 32767,
            leftStickY   = -32767,
            rightStickX  = 32767,
            rightStickY  = -32767,
            leftTrigger  = 255,
            rightTrigger = 255,
        });

        InputSystem.Update();

        Assert.That(gamepad.leftStick.x.ReadValue(), Is.EqualTo(0.9999).Within(0.001));
        Assert.That(gamepad.leftStick.y.ReadValue(), Is.EqualTo(0.9999).Within(0.001));
        Assert.That(gamepad.leftStick.up.ReadValue(), Is.EqualTo(0.9999).Within(0.001));
        Assert.That(gamepad.leftStick.down.ReadValue(), Is.EqualTo(0.0).Within(0.001));
        Assert.That(gamepad.leftStick.right.ReadValue(), Is.EqualTo(0.9999).Within(0.001));
        Assert.That(gamepad.leftStick.left.ReadValue(), Is.EqualTo(0.0).Within(0.001));

        Assert.That(gamepad.rightStick.x.ReadValue(), Is.EqualTo(0.9999).Within(0.001));
        Assert.That(gamepad.rightStick.y.ReadValue(), Is.EqualTo(0.9999).Within(0.001));
        Assert.That(gamepad.rightStick.up.ReadValue(), Is.EqualTo(0.9999).Within(0.001));
        Assert.That(gamepad.rightStick.down.ReadValue(), Is.EqualTo(0.0).Within(0.001));
        Assert.That(gamepad.rightStick.right.ReadValue(), Is.EqualTo(0.9999).Within(0.001));
        Assert.That(gamepad.rightStick.left.ReadValue(), Is.EqualTo(0.0).Within(0.001));

        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(1));
        Assert.That(gamepad.rightTrigger.ReadValue(), Is.EqualTo(1));

        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.A), gamepad.aButton);
        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.A), gamepad.buttonSouth);
        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.B), gamepad.bButton);
        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.B), gamepad.buttonEast);
        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.X), gamepad.xButton);
        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.X), gamepad.buttonWest);
        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.Y), gamepad.yButton);
        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.Y), gamepad.buttonNorth);

        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.DPadDown), gamepad.dpad.down);
        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.DPadUp), gamepad.dpad.up);
        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.DPadLeft), gamepad.dpad.left);
        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.DPadRight), gamepad.dpad.right);

        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.LeftThumbstickPress), gamepad.leftStickButton);
        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.RightThumbstickPress), gamepad.rightStickButton);

        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.LeftShoulder), gamepad.leftShoulder);
        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.RightShoulder), gamepad.rightShoulder);

        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.Start), gamepad.menu);
        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.Start), gamepad.startButton);
        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.Select), gamepad.view);
        AssertButtonPress(gamepad, new XInputControllerOSXState().WithButton(XInputControllerOSXState.Button.Select), gamepad.selectButton);
    }
    public void Analytics_ReceivesStartupEventOnFirstUpdate()
    {
        string receivedName = null;
        object receivedData = null;

        testRuntime.onSendAnalyticsEvent =
            (name, data) =>
        {
            Assert.That(receivedName, Is.Null);
            receivedName = name;
            receivedData = data;
        };

        // Add some data to the system.
        testRuntime.ReportNewInputDevice(new InputDeviceDescription
        {
            product       = "TestProductA",
            manufacturer  = "TestManufacturerA",
            deviceClass   = "Mouse",
            interfaceName = "TestA"
        }.ToJson());
        testRuntime.ReportNewInputDevice(new InputDeviceDescription
        {
            product       = "TestProductB",
            manufacturer  = "TestManufacturerB",
            deviceClass   = "Keyboard",
            interfaceName = "TestB"
        }.ToJson());
        testRuntime.ReportNewInputDevice(new InputDeviceDescription
        {
            product       = "TestProductC",
            manufacturer  = "TestManufacturerC",
            deviceClass   = "Unknown",
            interfaceName = "Other"
        }.ToJson());
        InputSystem.AddDevice <Gamepad>();

        InputSystem.Update();

        Assert.That(receivedName, Is.EqualTo(InputAnalytics.kEventStartup));
        Assert.That(receivedData, Is.TypeOf <InputAnalytics.StartupEventData>());

        var startupData = (InputAnalytics.StartupEventData)receivedData;

        Assert.That(startupData.version, Is.EqualTo(InputSystem.version.ToString()));
        Assert.That(startupData.devices, Is.Not.Null.And.Length.EqualTo(3));
        Assert.That(startupData.unrecognized_devices, Is.Not.Null.And.Length.EqualTo(1));

        Assert.That(startupData.devices[0].product, Is.Null);
        Assert.That(startupData.devices[0].@interface, Is.Null);
        Assert.That(startupData.devices[0].layout, Is.EqualTo("Gamepad"));
        Assert.That(startupData.devices[0].native, Is.False);

        Assert.That(startupData.devices[1].product, Is.EqualTo("TestManufacturerA TestProductA"));
        Assert.That(startupData.devices[1].@interface, Is.EqualTo("TestA"));
        Assert.That(startupData.devices[1].layout, Is.EqualTo("Mouse"));
        Assert.That(startupData.devices[1].native, Is.True);

        Assert.That(startupData.devices[2].product, Is.EqualTo("TestManufacturerB TestProductB"));
        Assert.That(startupData.devices[2].@interface, Is.EqualTo("TestB"));
        Assert.That(startupData.devices[2].layout, Is.EqualTo("Keyboard"));
        Assert.That(startupData.devices[2].native, Is.True);

        Assert.That(startupData.unrecognized_devices[0].product, Is.EqualTo("TestManufacturerC TestProductC"));
        Assert.That(startupData.unrecognized_devices[0].@interface, Is.EqualTo("Other"));
        Assert.That(startupData.unrecognized_devices[0].layout, Is.EqualTo("Unknown"));
        Assert.That(startupData.unrecognized_devices[0].native, Is.True);
    }
 public void LoadScene()
 {
     // Load game scene
     SceneManager.LoadScene(SceneName.SAVE_ONE_BALL_SCENE);
     keyboard = InputSystem.AddDevice <Keyboard>();
 }
 public virtual InputDevice AddDevice(string layout, string name = null, string variants = null)
 {
     return(InputSystem.AddDevice(layout, name, variants));
 }
Пример #28
0
    public void Devices_SupportsDualShockAsHID()
    {
#if !UNITY_WSA
        var device = InputSystem.AddDevice(new InputDeviceDescription
        {
            product       = "Wireless Controller",
            manufacturer  = "Sony Interactive Entertainment",
            interfaceName = "HID",
        });
#else // UWP requires different query logic (manufacture not available)
        var device = InputSystem.AddDevice(new InputDeviceDescription
        {
            product       = "Wireless Controller",
            interfaceName = "HID",
            capabilities  = new HID.HIDDeviceDescriptor
            {
                vendorId = 0x054C, // Sony
            }.ToJson()
        });
#endif

        Assert.That(device, Is.AssignableTo <DualShockGamepad>());
        var gamepad = (DualShockGamepad)device;

        InputSystem.QueueStateEvent(gamepad,
                                    new DualShockHIDInputReport
        {
            leftStickX   = 32,
            leftStickY   = 64,
            rightStickX  = 128,
            rightStickY  = 255,
            leftTrigger  = 20,
            rightTrigger = 40,
            buttons1     = 0xf7, // Low order 4 bits is Dpad but effectively uses only 3 bits.
            buttons2     = 0xff,
            buttons3     = 0xff
        });
        InputSystem.Update();

        Assert.That(gamepad.leftStick.x.ReadValue(), Is.EqualTo(NormalizeProcessor.Normalize(32 / 255.0f, 0f, 1f, 0.5f)).Within(0.00001));
        Assert.That(gamepad.leftStick.y.ReadValue(), Is.EqualTo(-NormalizeProcessor.Normalize(64 / 255.0f, 0f, 1f, 0.5f)).Within(0.00001));
        Assert.That(gamepad.rightStick.x.ReadValue(), Is.EqualTo(NormalizeProcessor.Normalize(128 / 255.0f, 0f, 1f, 0.5f)).Within(0.00001));
        Assert.That(gamepad.rightStick.y.ReadValue(), Is.EqualTo(-NormalizeProcessor.Normalize(255 / 255.0f, 0f, 1f, 0.5f)).Within(0.00001));
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(NormalizeProcessor.Normalize(20 / 255.0f, 0f, 1f, 0f)).Within(0.00001));
        Assert.That(gamepad.rightTrigger.ReadValue(), Is.EqualTo(NormalizeProcessor.Normalize(40 / 255.0f, 0f, 1f, 0f)).Within(0.00001));
        ////TODO: test button presses individually
        Assert.That(gamepad.buttonSouth.isPressed);
        Assert.That(gamepad.buttonEast.isPressed);
        Assert.That(gamepad.buttonWest.isPressed);
        Assert.That(gamepad.buttonNorth.isPressed);
        Assert.That(gamepad.squareButton.isPressed);
        Assert.That(gamepad.triangleButton.isPressed);
        Assert.That(gamepad.circleButton.isPressed);
        Assert.That(gamepad.crossButton.isPressed);
        Assert.That(gamepad.startButton.isPressed);
        Assert.That(gamepad.selectButton.isPressed);
        Assert.That(gamepad.dpad.up.isPressed); // Dpad uses enumerated values, not a bitfield; 0x7 is up left.
        Assert.That(gamepad.dpad.down.isPressed, Is.False);
        Assert.That(gamepad.dpad.left.isPressed);
        Assert.That(gamepad.dpad.right.isPressed, Is.False);
        Assert.That(gamepad.leftShoulder.isPressed);
        Assert.That(gamepad.rightShoulder.isPressed);
        Assert.That(gamepad.leftStickButton.isPressed);
        Assert.That(gamepad.rightStickButton.isPressed);
        Assert.That(gamepad.touchpadButton.isPressed);

        // Sensors not (yet?) supported. Needs figuring out how to interpret the HID data.
    }
Пример #29
0
    public unsafe void Devices_CanSetNPadVibrationMotorValues()
    {
        var controller = InputSystem.AddDevice <NPad>();

        NPadDeviceIOCTLOutputCommand?receivedCommand = null;

        unsafe
        {
            runtime.SetDeviceCommandCallback(controller.id,
                                             (id, commandPtr) =>
            {
                if (commandPtr->type == NPadDeviceIOCTLOutputCommand.Type)
                {
                    Assert.That(receivedCommand.HasValue, Is.False);
                    receivedCommand = *((NPadDeviceIOCTLOutputCommand *)commandPtr);
                    return(1);
                }

                Assert.Fail("Received wrong type of command");
                return(InputDeviceCommand.kGenericFailure);
            });
        }
        controller.SetMotorSpeeds(0.1234f, 0.5678f);

        Assert.That(receivedCommand.HasValue, Is.True);
        Assert.That(receivedCommand.Value.positionFlags, Is.EqualTo(0xFF));
        Assert.That(receivedCommand.Value.amplitudeLow, Is.EqualTo(0.1234f));
        Assert.That(receivedCommand.Value.frequencyLow, Is.EqualTo(NPadDeviceIOCTLOutputCommand.kDefaultFrequencyLow));
        Assert.That(receivedCommand.Value.amplitudeHigh, Is.EqualTo(0.5678f));
        Assert.That(receivedCommand.Value.frequencyHigh, Is.EqualTo(NPadDeviceIOCTLOutputCommand.kDefaultFrequencyHigh));

        receivedCommand = null;
        controller.SetMotorSpeeds(0.1234f, 56.78f, 0.9012f, 345.6f);

        Assert.That(receivedCommand.HasValue, Is.True);
        Assert.That(receivedCommand.Value.positionFlags, Is.EqualTo(0xFF));
        Assert.That(receivedCommand.Value.amplitudeLow, Is.EqualTo(0.1234f));
        Assert.That(receivedCommand.Value.frequencyLow, Is.EqualTo(56.78f));
        Assert.That(receivedCommand.Value.amplitudeHigh, Is.EqualTo(0.9012f));
        Assert.That(receivedCommand.Value.frequencyHigh, Is.EqualTo(345.6f));

        receivedCommand = null;
        controller.SetMotorSpeedLeft(0.1234f, 56.78f, 0.9012f, 345.6f);

        Assert.That(receivedCommand.HasValue, Is.True);
        Assert.That(receivedCommand.Value.positionFlags, Is.EqualTo(0x02));
        Assert.That(receivedCommand.Value.amplitudeLow, Is.EqualTo(0.1234f));
        Assert.That(receivedCommand.Value.frequencyLow, Is.EqualTo(56.78f));
        Assert.That(receivedCommand.Value.amplitudeHigh, Is.EqualTo(0.9012f));
        Assert.That(receivedCommand.Value.frequencyHigh, Is.EqualTo(345.6f));

        receivedCommand = null;
        controller.SetMotorSpeedRight(0.1234f, 56.78f, 0.9012f, 345.6f);

        Assert.That(receivedCommand.HasValue, Is.True);
        Assert.That(receivedCommand.Value.positionFlags, Is.EqualTo(0x04));
        Assert.That(receivedCommand.Value.amplitudeLow, Is.EqualTo(0.1234f));
        Assert.That(receivedCommand.Value.frequencyLow, Is.EqualTo(56.78f));
        Assert.That(receivedCommand.Value.amplitudeHigh, Is.EqualTo(0.9012f));
        Assert.That(receivedCommand.Value.frequencyHigh, Is.EqualTo(345.6f));
    }
    public void State_CanSetUpMonitorsForStateChanges()
    {
        var gamepad = InputSystem.AddDevice <Gamepad>();

        var          monitorFired    = false;
        InputControl receivedControl = null;
        double?      receivedTime    = null;

        var monitor = InputSystem.AddStateChangeMonitor(gamepad.leftStick,
                                                        (control, time, monitorIndex) =>
        {
            Assert.That(!monitorFired);
            monitorFired    = true;
            receivedControl = control;
            receivedTime    = time;
        });

        // Left stick only.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftStick = new Vector2(0.5f, 0.5f)
        }, 0.5);
        InputSystem.Update();

        Assert.That(monitorFired, Is.True);
        Assert.That(receivedControl, Is.SameAs(gamepad.leftStick));
        Assert.That(receivedTime.Value, Is.EqualTo(0.5).Within(0.000001));

        monitorFired    = false;
        receivedControl = null;
        receivedTime    = 0;

        // Left stick again but with no value change.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftStick = new Vector2(0.5f, 0.5f)
        }, 0.6);
        InputSystem.Update();

        Assert.That(monitorFired, Is.False);

        // Left and right stick.
        InputSystem.QueueStateEvent(gamepad,
                                    new GamepadState {
            rightStick = new Vector2(0.75f, 0.75f), leftStick = new Vector2(0.75f, 0.75f)
        }, 0.7);
        InputSystem.Update();

        Assert.That(monitorFired, Is.True);
        Assert.That(receivedControl, Is.SameAs(gamepad.leftStick));
        Assert.That(receivedTime.Value, Is.EqualTo(0.7).Within(0.000001));

        monitorFired    = false;
        receivedControl = null;
        receivedTime    = 0;

        // Right stick only.
        InputSystem.QueueStateEvent(gamepad,
                                    new GamepadState {
            rightStick = new Vector2(0.5f, 0.5f), leftStick = new Vector2(0.75f, 0.75f)
        }, 0.8);
        InputSystem.Update();

        Assert.That(monitorFired, Is.False);

        // Component control of left stick.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftStick = new Vector2(0.75f, 0.5f)
        }, 0.9);
        InputSystem.Update();

        Assert.That(monitorFired, Is.True);
        ////REVIEW: do we want to be able to detect the child control that actually changed? could be multiple, though
        Assert.That(receivedControl, Is.SameAs(gamepad.leftStick));
        Assert.That(receivedTime.Value, Is.EqualTo(0.9).Within(0.000001));

        // Remove state monitor and change leftStick again.
        InputSystem.RemoveStateChangeMonitor(gamepad.leftStick, monitor);

        monitorFired    = false;
        receivedControl = null;
        receivedTime    = 0;

        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftStick = new Vector2(0.0f, 0.0f)
        }, 1.0);
        InputSystem.Update();

        Assert.That(monitorFired, Is.False);
    }