static void Register()
 {
     InputSystem.RegisterDeviceProfile <OpenVRControllerProfile>();
 }
Example #2
0
            private void OnEvent(InputEventPtr eventPtr)
            {
                // Ignore if not a state event.
                if (!eventPtr.IsA <StateEvent>() && !eventPtr.IsA <DeltaStateEvent>())
                {
                    return;
                }

                // Fetch device.
                var device = InputSystem.GetDeviceById(eventPtr.deviceId);

                if (device == null)
                {
                    return;
                }

                // Go through controls and see if there's anything interesting in the event.
                var controls     = device.allControls;
                var controlCount = controls.Count;

                for (var i = 0; i < controlCount; ++i)
                {
                    var control = controls[i];

                    ////TODO: skip noisy controls

                    // Skip controls that have no state in the event.
                    var statePtr = control.GetStatePtrFromStateEvent(eventPtr);
                    if (statePtr == IntPtr.Zero)
                    {
                        continue;
                    }

                    // If we're expecting controls of a certain type, skip if control isn't of
                    // the right type.
                    if (m_ControlType != null && !m_ControlType.IsInstanceOfType(control))
                    {
                        continue;
                    }

                    // If we're expecting controls to be based on a specific layout, skip if control
                    // isn't based on that layout.
                    if (!m_ExpectedLayout.IsEmpty() &&
                        InputControlLayout.s_Layouts.IsBasedOn(m_ExpectedLayout, control.m_Layout))
                    {
                        continue;
                    }

                    // Skip controls that are in their default state.
                    // NOTE: This is the cheapest check with respect to looking at actual state. So
                    //       do this first before looking further at the state.
                    if (control.CheckStateIsAtDefault(statePtr))
                    {
                        continue;
                    }

                    // Skip controls that have no effective value change.
                    // NOTE: This will run the full processor stack and is move involved.
                    if (!control.HasValueChangeIn(statePtr))
                    {
                        continue;
                    }

                    // If it's the control that cancels, abort the operation now.
                    if (!string.IsNullOrEmpty(m_CancelBinding) && InputControlPath.Matches(m_CancelBinding, control))
                    {
                        OnCancel();
                        break;
                    }

                    m_Candidates.Add(control);
                    OnComplete();
                    break;
                }
            }
 static void Register()
 {
     InputSystem.RegisterDeviceProfile <TangoXRProfile>();
 }
        /// <summary>
        /// Resolve and add all bindings and actions from the given map.
        /// </summary>
        /// <param name="map"></param>
        /// <remarks>
        /// This is where all binding resolution happens for actions. The method walks through the binding array
        /// in <paramref name="map"/> and adds any controls, interactions, processors, and composites as it goes.
        /// </remarks>
        public unsafe void AddActionMap(InputActionMap map)
        {
            Debug.Assert(map != null);

            var actionsInThisMap      = map.m_Actions;
            var bindingsInThisMap     = map.m_Bindings;
            var bindingCountInThisMap = bindingsInThisMap?.Length ?? 0;
            var actionCountInThisMap  = actionsInThisMap?.Length ?? 0;
            var mapIndex = totalMapCount;

            // Keep track of indices for this map.
            var actionStartIndex      = totalActionCount;
            var bindingStartIndex     = totalBindingCount;
            var controlStartIndex     = totalControlCount;
            var interactionStartIndex = totalInteractionCount;
            var processorStartIndex   = totalProcessorCount;
            var compositeStartIndex   = totalCompositeCount;

            // Allocate an initial block of memory. We probably will have to re-allocate once
            // at the end to accommodate interactions and controls added from the map.
            var newMemory = new InputActionState.UnmanagedMemory();

            newMemory.Allocate(
                mapCount: totalMapCount + 1,
                actionCount: totalActionCount + actionCountInThisMap,
                bindingCount: totalBindingCount + bindingCountInThisMap,
                // We reallocate for the following once we know the final count.
                interactionCount: totalInteractionCount,
                compositeCount: totalCompositeCount,
                controlCount: totalControlCount);
            if (memory.isAllocated)
            {
                newMemory.CopyDataFrom(memory);
            }

            ////TODO: make sure composite objects get all the bindings they need
            ////TODO: handle case where we have bindings resolving to the same control
            ////      (not so clear cut what to do there; each binding may have a different interaction setup, for example)
            var         currentCompositeBindingIndex     = InputActionState.kInvalidIndex;
            var         currentCompositeIndex            = InputActionState.kInvalidIndex;
            var         currentCompositePartIndex        = 0;
            var         currentCompositeActionIndexInMap = InputActionState.kInvalidIndex;
            InputAction currentCompositeAction           = null;
            var         bindingMaskOnThisMap             = map.m_BindingMask;
            var         devicesForThisMap = map.devices;

            // Can't use `using` as we need to use it with `ref`.
            var resolvedControls = new InputControlList <InputControl>(Allocator.Temp);

            // We gather all controls in temporary memory and then move them over into newMemory once
            // we're done resolving.
            try
            {
                var bindingStatesPtr = newMemory.bindingStates;
                for (var n = 0; n < bindingCountInThisMap; ++n)
                {
                    ref var unresolvedBinding = ref bindingsInThisMap[n];
                    var     bindingIndex      = bindingStartIndex + n;
                    var     isComposite       = unresolvedBinding.isComposite;
                    var     isPartOfComposite = !isComposite && unresolvedBinding.isPartOfComposite;
                    var     bindingState      = &bindingStatesPtr[bindingIndex];

                    try
                    {
                        ////TODO: if it's a composite, check if any of the children matches our binding masks (if any) and skip composite if none do

                        // Set binding state to defaults.
                        bindingState->mapIndex = totalMapCount;
                        bindingState->compositeOrCompositeBindingIndex = InputActionState.kInvalidIndex;
                        bindingState->actionIndex = InputActionState.kInvalidIndex;

                        // Skip binding if it is disabled (path is empty string).
                        var path = unresolvedBinding.effectivePath;
                        if (unresolvedBinding.path == "")
                        {
                            continue;
                        }

                        // Skip binding if it doesn't match with our binding mask (might be empty).
                        if (!isComposite && bindingMask != null && !bindingMask.Value.Matches(ref unresolvedBinding))
                        {
                            continue;
                        }

                        // Skip binding if it doesn't match the binding mask on the map (might be empty).
                        if (!isComposite && bindingMaskOnThisMap != null &&
                            !bindingMaskOnThisMap.Value.Matches(ref unresolvedBinding))
                        {
                            continue;
                        }

                        // Try to find action.
                        //
                        // NOTE: We ignore actions on bindings that are part of composites. We only allow
                        //       actions to be triggered from the composite itself.
                        var         actionIndexInMap = InputActionState.kInvalidIndex;
                        var         actionName       = unresolvedBinding.action;
                        InputAction action           = null;
                        if (!isPartOfComposite)
                        {
                            if (!string.IsNullOrEmpty(actionName))
                            {
                                ////REVIEW: should we fail here if we don't manage to find the action
                                actionIndexInMap = map.TryGetActionIndex(actionName);
                            }
                            else if (map.m_SingletonAction != null)
                            {
                                // Special-case for singleton actions that don't have names.
                                actionIndexInMap = 0;
                            }

                            if (actionIndexInMap != InputActionState.kInvalidIndex)
                            {
                                action = actionsInThisMap[actionIndexInMap];
                            }
                        }
                        else
                        {
                            actionIndexInMap = currentCompositeActionIndexInMap;
                            action           = currentCompositeAction;
                        }

                        // Skip binding if it doesn't match the binding mask on the action (might be empty).
                        if (!isComposite && action?.m_BindingMask != null &&
                            !action.m_BindingMask.Value.Matches(ref unresolvedBinding))
                        {
                            continue;
                        }

                        // Instantiate processors.
                        var firstProcessorIndex = InputActionState.kInvalidIndex;
                        var numProcessors       = 0;
                        var processorString     = unresolvedBinding.effectiveProcessors;
                        if (!string.IsNullOrEmpty(processorString))
                        {
                            // Add processors from binding.
                            firstProcessorIndex = ResolveProcessors(processorString);
                            if (firstProcessorIndex != InputActionState.kInvalidIndex)
                            {
                                numProcessors = totalProcessorCount - firstProcessorIndex;
                            }
                        }
                        if (action != null && !string.IsNullOrEmpty(action.m_Processors))
                        {
                            // Add processors from action.
                            var index = ResolveProcessors(action.m_Processors);
                            if (index != InputActionState.kInvalidIndex)
                            {
                                if (firstProcessorIndex == InputActionState.kInvalidIndex)
                                {
                                    firstProcessorIndex = index;
                                }
                                numProcessors += totalProcessorCount - index;
                            }
                        }

                        // Instantiate interactions.
                        var firstInteractionIndex = InputActionState.kInvalidIndex;
                        var numInteractions       = 0;
                        var interactionString     = unresolvedBinding.effectiveInteractions;
                        if (!string.IsNullOrEmpty(interactionString))
                        {
                            // Add interactions from binding.
                            firstInteractionIndex = ResolveInteractions(interactionString);
                            if (firstInteractionIndex != InputActionState.kInvalidIndex)
                            {
                                numInteractions = totalInteractionCount - firstInteractionIndex;
                            }
                        }
                        if (action != null && !string.IsNullOrEmpty(action.m_Interactions))
                        {
                            // Add interactions from action.
                            var index = ResolveInteractions(action.m_Interactions);
                            if (index != InputActionState.kInvalidIndex)
                            {
                                if (firstInteractionIndex == InputActionState.kInvalidIndex)
                                {
                                    firstInteractionIndex = index;
                                }
                                numInteractions += totalInteractionCount - index;
                            }
                        }

                        // If it's the start of a composite chain, create the composite.
                        if (isComposite)
                        {
                            var actionIndexForComposite = actionIndexInMap != InputActionState.kInvalidIndex
                                ? actionStartIndex + actionIndexInMap
                                : InputActionState.kInvalidIndex;

                            // Instantiate. For composites, the path is the name of the composite.
                            var composite = InstantiateBindingComposite(unresolvedBinding.path);
                            currentCompositeIndex =
                                ArrayHelpers.AppendWithCapacity(ref composites, ref totalCompositeCount, composite);
                            currentCompositeBindingIndex     = bindingIndex;
                            currentCompositeAction           = action;
                            currentCompositeActionIndexInMap = actionIndexInMap;

                            *bindingState = new InputActionState.BindingState
                            {
                                actionIndex = actionIndexForComposite,
                                compositeOrCompositeBindingIndex = currentCompositeIndex,
                                processorStartIndex   = firstProcessorIndex,
                                processorCount        = numProcessors,
                                interactionCount      = numInteractions,
                                interactionStartIndex = firstInteractionIndex,
                                mapIndex    = totalMapCount,
                                isComposite = true,
                                // Record where the controls for parts of the composite start.
                                controlStartIndex = memory.controlCount + resolvedControls.Count,
                            };

                            // The composite binding entry itself does not resolve to any controls.
                            // It creates a composite binding object which is then populated from
                            // subsequent bindings.
                            continue;
                        }

                        // If we've reached the end of a composite chain, finish
                        // off the current composite.
                        if (!isPartOfComposite && currentCompositeBindingIndex != InputActionState.kInvalidIndex)
                        {
                            currentCompositePartIndex        = 0;
                            currentCompositeBindingIndex     = InputActionState.kInvalidIndex;
                            currentCompositeIndex            = InputActionState.kInvalidIndex;
                            currentCompositeAction           = null;
                            currentCompositeActionIndexInMap = InputActionState.kInvalidIndex;
                        }

                        // Look up controls.
                        //
                        // NOTE: We continuously add controls here to `resolvedControls`. Once we've completed our
                        //       pass over the bindings in the map, `resolvedControls` will have all the controls for
                        //       the current map.
                        var firstControlIndex = memory.controlCount + resolvedControls.Count;
                        var numControls       = 0;
                        if (devicesForThisMap != null)
                        {
                            // Search in devices for only this map.
                            var list = devicesForThisMap.Value;
                            for (var i = 0; i < list.Count; ++i)
                            {
                                var device = list[i];
                                if (!device.added)
                                {
                                    continue; // Skip devices that have been removed.
                                }
                                numControls += InputControlPath.TryFindControls(device, path, 0, ref resolvedControls);
                            }
                        }
                        else
                        {
                            // Search globally.
                            numControls = InputSystem.FindControls(path, ref resolvedControls);
                        }

                        // If the binding is part of a composite, pass the resolved controls
                        // on to the composite.
                        var actionIndexForBinding = InputActionState.kInvalidIndex;
                        if (isPartOfComposite && currentCompositeBindingIndex != InputActionState.kInvalidIndex && numControls > 0)
                        {
                            // Make sure the binding is named. The name determines what in the composite
                            // to bind to.
                            if (string.IsNullOrEmpty(unresolvedBinding.name))
                            {
                                throw new Exception(
                                          $"Binding with path '{path}' that is part of composite '{composites[currentCompositeIndex]}' is missing a name");
                            }

                            // Install the controls on the binding.
                            BindControlInComposite(composites[currentCompositeIndex], unresolvedBinding.name,
                                                   ref currentCompositePartIndex);

                            // Keep track of total number of controls bound in the composite.
                            bindingStatesPtr[currentCompositeBindingIndex].controlCount += numControls;

                            // Force action index on part binding to be same as that of composite.
                            actionIndexForBinding = bindingStatesPtr[currentCompositeBindingIndex].actionIndex;
                        }
                        else if (actionIndexInMap != InputActionState.kInvalidIndex)
                        {
                            actionIndexForBinding = actionStartIndex + actionIndexInMap;
                        }

                        // Add entry for resolved binding.
                        *bindingState = new InputActionState.BindingState
                        {
                            controlStartIndex                = firstControlIndex,
                            controlCount                     = numControls,
                            interactionStartIndex            = firstInteractionIndex,
                            interactionCount                 = numInteractions,
                            processorStartIndex              = firstProcessorIndex,
                            processorCount                   = numProcessors,
                            isPartOfComposite                = unresolvedBinding.isPartOfComposite,
                            partIndex                        = currentCompositePartIndex,
                            actionIndex                      = actionIndexForBinding,
                            compositeOrCompositeBindingIndex = currentCompositeBindingIndex,
                            mapIndex = totalMapCount,
                        };
                    }
                    catch (Exception exception)
                    {
                        Debug.LogError(
                            $"{exception.GetType().Name} while resolving binding '{unresolvedBinding}' in action map '{map}'");
                        Debug.LogException(exception);

                        // Don't swallow exceptions that indicate something is wrong in the code rather than
                        // in the data.
                        if (exception.IsExceptionIndicatingBugInCode())
                        {
                            throw exception;
                        }
                    }
                }

                // Re-allocate memory to accommodate controls and interaction states. The count for those
                // we only know once we've completed all resolution.
                var controlCountInThisMap = resolvedControls.Count;
                var newTotalControlCount  = memory.controlCount + controlCountInThisMap;
                if (newMemory.interactionCount != totalInteractionCount ||
                    newMemory.compositeCount != totalCompositeCount ||
                    newMemory.controlCount != newTotalControlCount)
                {
                    var finalMemory = new InputActionState.UnmanagedMemory();

                    finalMemory.Allocate(
                        mapCount: newMemory.mapCount,
                        actionCount: newMemory.actionCount,
                        bindingCount: newMemory.bindingCount,
                        controlCount: newTotalControlCount,
                        interactionCount: totalInteractionCount,
                        compositeCount: totalCompositeCount);

                    finalMemory.CopyDataFrom(newMemory);

                    newMemory.Dispose();
                    newMemory = finalMemory;
                }

                // Add controls to array.
                var controlCountInArray = memory.controlCount;
                ArrayHelpers.AppendListWithCapacity(ref controls, ref controlCountInArray, resolvedControls);
                Debug.Assert(controlCountInArray == newTotalControlCount,
                             "Control array should have combined count of old and new controls");

                // Set up control to binding index mapping.
                for (var i = 0; i < bindingCountInThisMap; ++i)
                {
                    var bindingState = &bindingStatesPtr[bindingStartIndex + i];
                    var numControls  = bindingState->controlCount;
                    var startIndex   = bindingState->controlStartIndex;
                    for (var n = 0; n < numControls; ++n)
                    {
                        newMemory.controlIndexToBindingIndex[startIndex + n] = bindingStartIndex + i;
                    }
                }

                // Initialize initial interaction states.
                for (var i = memory.interactionCount; i < newMemory.interactionCount; ++i)
                {
                    newMemory.interactionStates[i].phase = InputActionPhase.Waiting;
                }

                // Initialize action data.
                var runningIndexInBindingIndices = memory.bindingCount;
                for (var i = 0; i < actionCountInThisMap; ++i)
                {
                    var action      = actionsInThisMap[i];
                    var actionIndex = actionStartIndex + i;

                    // Correlate action with its trigger state.
                    action.m_ActionIndex = actionIndex;

                    // Collect bindings for action.
                    var bindingStartIndexForAction      = runningIndexInBindingIndices;
                    var bindingCountForAction           = 0;
                    var numPossibleConcurrentActuations = 0;
                    var haveCompositeBinding            = false;
                    for (var n = 0; n < bindingCountInThisMap; ++n)
                    {
                        var bindingIndex = bindingStartIndex + n;
                        var bindingState = &newMemory.bindingStates[bindingIndex];
                        if (bindingState->actionIndex != actionIndex)
                        {
                            continue;
                        }
                        if (bindingState->isPartOfComposite)
                        {
                            continue;
                        }

                        Debug.Assert(bindingIndex <= ushort.MaxValue, "Binding index exceeds limit");
                        newMemory.actionBindingIndices[runningIndexInBindingIndices] = (ushort)bindingIndex;
                        ++runningIndexInBindingIndices;
                        ++bindingCountForAction;

                        // Keep track of how many concurrent actuations we may be seeing on the action so that
                        // we know whether we need to enable conflict resolution or not.
                        if (bindingState->isComposite)
                        {
                            // Composite binding. Actuates as a whole. Check if the composite has successfully
                            // resolved any controls. If so, it adds one possible actuation.
                            if (bindingState->controlCount > 0)
                            {
                                ++numPossibleConcurrentActuations;
                            }
                        }
                        else
                        {
                            // Normal binding. Every successfully resolved control results in one possible actuation.
                            numPossibleConcurrentActuations += bindingState->controlCount;
                        }
                    }
                    Debug.Assert(bindingStartIndexForAction < ushort.MaxValue, "Binding start index on action exceeds limit");
                    Debug.Assert(bindingCountForAction < ushort.MaxValue, "Binding count on action exceeds limit");
                    newMemory.actionBindingIndicesAndCounts[i * 2]     = (ushort)bindingStartIndexForAction;
                    newMemory.actionBindingIndicesAndCounts[i * 2 + 1] = (ushort)bindingCountForAction;

                    // See if we may need conflict resolution on this action. Never needed for pass-through actions.
                    // Otherwise, if we have more than one bound control or have several bindings and one of them
                    // is a composite, we enable it.
                    var isPassThroughAction       = action.passThrough;
                    var mayNeedConflictResolution = !isPassThroughAction && numPossibleConcurrentActuations > 1;

                    // Initialize initial trigger state.
                    newMemory.actionStates[actionIndex] =
                        new InputActionState.TriggerState
                    {
                        phase                     = InputActionPhase.Disabled,
                        mapIndex                  = mapIndex,
                        controlIndex              = InputActionState.kInvalidIndex,
                        interactionIndex          = InputActionState.kInvalidIndex,
                        continuous                = action.continuous,
                        passThrough               = isPassThroughAction,
                        mayNeedConflictResolution = mayNeedConflictResolution,
                    };
                }

                // Store indices for map.
                newMemory.mapIndices[mapIndex] =
                    new InputActionState.ActionMapIndices
                {
                    actionStartIndex      = actionStartIndex,
                    actionCount           = actionCountInThisMap,
                    controlStartIndex     = controlStartIndex,
                    controlCount          = controlCountInThisMap,
                    bindingStartIndex     = bindingStartIndex,
                    bindingCount          = bindingCountInThisMap,
                    interactionStartIndex = interactionStartIndex,
                    interactionCount      = totalInteractionCount - interactionStartIndex,
                    processorStartIndex   = processorStartIndex,
                    processorCount        = totalProcessorCount - processorStartIndex,
                    compositeStartIndex   = compositeStartIndex,
                    compositeCount        = totalCompositeCount - compositeStartIndex,
                };
                map.m_MapIndexInState = mapIndex;
                var finalActionMapCount = memory.mapCount;
                ArrayHelpers.AppendWithCapacity(ref maps, ref finalActionMapCount, map, capacityIncrement: 4);
                Debug.Assert(finalActionMapCount == newMemory.mapCount,
                             "Final action map count should match old action map count plus one");

                // As a final act, swap the new memory in.
                memory.Dispose();
                memory = newMemory;
            }
Example #5
0
        public static void ControlField <C, T>(Rect position, InputBinding <C, T> binding, GUIContent label, IControlDomainSource domainSource, Action <InputBinding <C, T> > action, SerializedProperty prop = null) where C : InputControl <T>
        {
            if (prop != null)
            {
                label = EditorGUI.BeginProperty(position, label, prop);
            }

            position.height = EditorGUIUtility.singleLineHeight;

            Rect buttonPosition = EditorGUI.PrefixLabel(position, label);
            Rect detectPosition = buttonPosition;

            ControlScheme scheme           = domainSource as ControlScheme;
            bool          detectionSupport = (scheme != null);

            if (detectionSupport)
            {
                detectPosition.xMin  = detectPosition.xMax - 20;
                buttonPosition.xMax -= (20 + 4);
            }

            if (EditorGUI.DropdownButton(buttonPosition, new GUIContent(GetName(binding, domainSource) ?? "None"), FocusType.Keyboard))
            {
                GenericMenu menu = GetMenu(
                    binding, domainSource,
                    a =>
                {
                    if (prop != null)
                    {
                        Undo.RecordObjects(prop.serializedObject.targetObjects, "Control");
                    }

                    action(a);

                    if (prop != null)
                    {
                        // Flushing seems necessaary to have prefab property override status change without lag.
                        Undo.FlushUndoRecordObjects();
                        prop.serializedObject.SetIsDifferentCacheDirty();
                    }
                });
                menu.DropDown(buttonPosition);

                // GenericMenu doesn't modify GUI.changed because it relies on a callback, so let's assume that something was changed, so target object dirtying doesn't go missing
                GUI.changed = true;
            }

            if (detectionSupport)
            {
                EditorGUI.BeginDisabledGroup(s_Binding != null);
                //if (Event.current.type == EventType.repaint)
                //    EditorStyles.miniButton.Draw(detectPosition, "O", false, false, s_Binding == binding, false);
                if (GUI.Toggle(detectPosition, s_Binding == binding, "O", EditorStyles.miniButton) && s_Binding == null)
                {
                    EditorWindow window = EditorWindow.focusedWindow;
                    window.ShowNotification(new GUIContent("Waiting for input."));
                    s_BindingListener = (InputControl control) =>
                    {
                        if (!(control is C))
                        {
                            window.ShowNotification(new GUIContent("Incompatible control type."));
                            window.Repaint();
                            return(false);
                        }

                        DeviceSlot match = null;
                        Type       controlProviderType = control.provider.GetType();
                        for (int slotIndex = 0; slotIndex < scheme.deviceSlots.Count; slotIndex++)
                        {
                            Type deviceType = scheme.deviceSlots[slotIndex].type.value;
                            if (deviceType == null)
                            {
                                continue;
                            }
                            if (deviceType.IsAssignableFrom(controlProviderType))
                            {
                                match = scheme.deviceSlots[slotIndex];
                                break;
                            }
                        }
                        if (match == null)
                        {
                            window.ShowNotification(new GUIContent("Incompatible device type."));
                            window.Repaint();
                            return(false);
                        }

                        var newReference = new ControlReferenceBinding <C, T>();
                        newReference.deviceKey   = match.key;
                        newReference.controlHash = control.provider.GetHashForControlIndex(control.index);
                        action(newReference);

                        StopListening(window);

                        return(true);
                    };
                    InputSystem.ListenForBinding(s_BindingListener);
                    s_Binding = binding;

                    float time = Time.realtimeSinceStartup;
                    s_UpdateCallback = () => {
                        if (Time.realtimeSinceStartup > time + 3)
                        {
                            StopListening(window);
                        }
                    };
                    EditorApplication.update += s_UpdateCallback;
                }
                EditorGUI.EndDisabledGroup();
            }

            if (binding != null && !(binding is ControlReferenceBinding <C, T>))
            {
                EditorGUI.indentLevel++;
                position.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
                binding.OnGUI(position, domainSource);
                EditorGUI.indentLevel--;
            }

            if (prop != null)
            {
                EditorGUI.EndProperty();
            }
        }
        /// <summary>
        /// Resolve and add all bindings and actions from the given map.
        /// </summary>
        /// <param name="map"></param>
        /// <exception cref="Exception"></exception>
        public void AddActionMap(InputActionMap map)
        {
            Debug.Assert(map != null);
            Debug.Assert(map.m_MapIndex == InputActionMapState.kInvalidIndex);

            // Keep track of indices for this map.
            var bindingStartIndex     = totalBindingCount;
            var controlStartIndex     = totalControlCount;
            var interactionStartIndex = totalInteractionCount;
            var processorStartIndex   = totalProcessorCount;
            var compositeStartIndex   = totalCompositeCount;
            var actionStartIndex      = totalActionCount;

            // Allocate binding states.
            var bindingsInThisMap     = map.m_Bindings;
            var bindingCountInThisMap = bindingsInThisMap != null ? bindingsInThisMap.Length : 0;

            totalBindingCount += bindingCountInThisMap;
            ArrayHelpers.GrowBy(ref bindingStates, totalBindingCount);

            ////TODO: make sure composite objects get all the bindings they need
            ////TODO: handle case where we have bindings resolving to the same control
            ////      (not so clear cut what to do there; each binding may have a different interaction setup, for example)
            var currentCompositeBindingIndex = InputActionMapState.kInvalidIndex;
            var currentCompositeIndex        = InputActionMapState.kInvalidIndex;
            var actionsInThisMap             = map.m_Actions;
            var actionCountInThisMap         = actionsInThisMap != null ? actionsInThisMap.Length : 0;

            for (var n = 0; n < bindingCountInThisMap; ++n)
            {
                var unresolvedBinding = bindingsInThisMap[n];
                var bindingIndex      = bindingStartIndex + n;

                // Skip binding if it is disabled (path is empty string).
                var path = unresolvedBinding.effectivePath;
                if (unresolvedBinding.path == "")
                {
                    continue;
                }

                // Try to find action.
                var actionIndex = InputActionMapState.kInvalidIndex;
                var actionName  = unresolvedBinding.action;
                if (!string.IsNullOrEmpty(actionName))
                {
                    actionIndex = map.TryGetActionIndex(actionName);
                }
                else if (map.m_SingletonAction != null)
                {
                    // Special-case for singleton actions that don't have names.
                    actionIndex = 0;
                }

                // Instantiate processors.
                var firstProcessorIndex = 0;
                var numProcessors       = 0;
                var processors          = unresolvedBinding.effectiveProcessors;
                if (!string.IsNullOrEmpty(processors))
                {
                    firstProcessorIndex = ResolveProcessors(processors);
                    if (processors != null)
                    {
                        numProcessors = totalProcessorCount - firstProcessorIndex;
                    }
                }

                // Instantiate interactions.
                var firstInteractionIndex = 0;
                var numInteractions       = 0;
                var interactions          = unresolvedBinding.effectiveInteractions;
                if (!string.IsNullOrEmpty(interactions))
                {
                    firstInteractionIndex = ResolveInteractions(interactions);
                    if (interactionStates != null)
                    {
                        numInteractions = totalInteractionCount - firstInteractionIndex;
                    }
                }

                ////TODO: allow specifying parameters for composite on its path (same way as parameters work for interactions)
                // If it's the start of a composite chain, create the composite.
                if (unresolvedBinding.isComposite)
                {
                    ////REVIEW: what to do about interactions on composites?

                    // Instantiate. For composites, the path is the name of the composite.
                    var composite = InstantiateBindingComposite(unresolvedBinding.path);
                    currentCompositeIndex =
                        ArrayHelpers.AppendWithCapacity(ref composites, ref totalCompositeCount, composite);
                    currentCompositeBindingIndex = bindingIndex;
                    bindingStates[bindingIndex]  = new InputActionMapState.BindingState
                    {
                        actionIndex = actionIndex,
                        compositeOrCompositeBindingIndex = currentCompositeIndex,
                        processorStartIndex   = firstProcessorIndex,
                        processorCount        = numProcessors,
                        interactionCount      = numInteractions,
                        interactionStartIndex = firstInteractionIndex,
                        mapIndex = totalMapCount,
                    };

                    // The composite binding entry itself does not resolve to any controls.
                    // It creates a composite binding object which is then populated from
                    // subsequent bindings.
                    continue;
                }

                // If we've reached the end of a composite chain, finish
                // off the current composite.
                if (!unresolvedBinding.isPartOfComposite &&
                    currentCompositeBindingIndex != InputActionMapState.kInvalidIndex)
                {
                    currentCompositeBindingIndex = InputActionMapState.kInvalidIndex;
                    currentCompositeIndex        = InputActionMapState.kInvalidIndex;
                }

                // Look up controls.
                var firstControlIndex = totalControlCount;
                if (controls == null)
                {
                    controls = new InputControl[10];
                }
                var resolvedControls = new ArrayOrListWrapper <InputControl>(controls, totalControlCount);
                var numControls      = InputSystem.GetControls(path, ref resolvedControls);
                controls          = resolvedControls.array;
                totalControlCount = resolvedControls.count;

                // Add entry for resolved binding.
                bindingStates[bindingIndex] = new InputActionMapState.BindingState
                {
                    controlStartIndex                = firstControlIndex,
                    controlCount                     = numControls,
                    interactionStartIndex            = firstInteractionIndex,
                    interactionCount                 = numInteractions,
                    processorStartIndex              = firstProcessorIndex,
                    processorCount                   = numProcessors,
                    isPartOfComposite                = unresolvedBinding.isPartOfComposite,
                    actionIndex                      = actionIndex,
                    compositeOrCompositeBindingIndex = currentCompositeBindingIndex,
                    mapIndex = totalMapCount,
                };

                // If the binding is part of a composite, pass the resolve controls
                // on to the composite.
                if (unresolvedBinding.isPartOfComposite && currentCompositeBindingIndex != InputActionMapState.kInvalidIndex && numControls != 0)
                {
                    ////REVIEW: what should we do when a single binding in a composite resolves to multiple controls?
                    ////        if the composite has more than one bindable control, it's not readily apparent how we would group them
                    if (numControls > 1)
                    {
                        throw new NotImplementedException("Handling case where single binding in composite resolves to multiple controls");
                    }

                    // Make sure the binding is named. The name determines what in the composite
                    // to bind to.
                    if (string.IsNullOrEmpty(unresolvedBinding.name))
                    {
                        throw new Exception(string.Format(
                                                "Binding that is part of composite '{0}' is missing a name",
                                                composites[currentCompositeIndex]));
                    }

                    // Install the control on the binding.
                    BindControlInComposite(composites[currentCompositeIndex], unresolvedBinding.name,
                                           controls[firstControlIndex]);
                }
            }

            // Set up control to binding index mapping.
            var controlCountInThisMap = totalControlCount - controlStartIndex;

            ArrayHelpers.GrowBy(ref controlIndexToBindingIndex, controlCountInThisMap);
            for (var i = 0; i < bindingCountInThisMap; ++i)
            {
                var numControls = bindingStates[bindingStartIndex + i].controlCount;
                var startIndex  = bindingStates[bindingStartIndex + i].controlStartIndex;
                for (var n = 0; n < numControls; ++n)
                {
                    controlIndexToBindingIndex[startIndex + n] = i;
                }
            }

            // Store indices for map.
            var numMaps  = totalMapCount;
            var mapIndex = ArrayHelpers.AppendWithCapacity(ref maps, ref numMaps, map);

            ArrayHelpers.AppendWithCapacity(ref mapIndices, ref totalMapCount, new InputActionMapState.ActionMapIndices
            {
                actionStartIndex      = actionStartIndex,
                actionCount           = actionCountInThisMap,
                controlStartIndex     = controlStartIndex,
                controlCount          = controlCountInThisMap,
                bindingStartIndex     = bindingStartIndex,
                bindingCount          = bindingCountInThisMap,
                interactionStartIndex = interactionStartIndex,
                interactionCount      = totalInteractionCount - interactionStartIndex,
                processorStartIndex   = processorStartIndex,
                processorCount        = totalProcessorCount - processorStartIndex,
                compositeStartIndex   = compositeStartIndex,
                compositeCount        = totalCompositeCount - compositeStartIndex,
            });
            map.m_MapIndex = mapIndex;

            // Allocate action states.
            if (actionCountInThisMap > 0)
            {
                // Assign action indices.
                var actions = map.m_Actions;
                for (var i = 0; i < actionCountInThisMap; ++i)
                {
                    actions[i].m_ActionIndex = totalActionCount + i;
                }

                ArrayHelpers.GrowBy(ref actionStates, actionCountInThisMap);
                totalActionCount += actionCountInThisMap;
                for (var i = 0; i < actionCountInThisMap; ++i)
                {
                    actionStates[i].mapIndex = mapIndex;
                }
            }
        }
 static void Register()
 {
     InputSystem.RegisterDeviceProfile <OculusTouchProfile>();
 }
Example #8
0
        /// <summary>
        /// Perform the input action without having to know what it is bound to.
        /// </summary>
        /// <param name="action">An input action that is currently enabled and has controls it is bound to.</param>
        /// <remarks>
        /// Blindly triggering an action requires making a few assumptions. Actions are not built to be able to trigger
        /// without any input. This means that this method has to generate input on a control that the action is bound to.
        ///
        /// Note that this method has no understanding of the interactions that may be present on the action and thus
        /// does not know how they may affect the triggering of the action.
        /// </remarks>
        public void Trigger(InputAction action)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            if (!action.enabled)
            {
                throw new ArgumentException(
                          string.Format("Action '{0}' must be enabled in order to be able to trigger it", action), "action");
            }

            var controls = action.controls;

            if (controls.Count == 0)
            {
                throw new ArgumentException(
                          string.Format("Action '{0}' must be bound to controls in order to be able to trigger it", action), "action");
            }

            // See if we have a button we can trigger.
            for (var i = 0; i < controls.Count; ++i)
            {
                var button = controls[i] as ButtonControl;
                if (button == null)
                {
                    continue;
                }

                // We do, so flip its state and we're done.
                var           device = button.device;
                InputEventPtr inputEvent;
                using (StateEvent.From(device, out inputEvent))
                {
                    button.WriteValueInto(inputEvent, button.isPressed ? 0 : 1);
                    InputSystem.QueueEvent(inputEvent);
                    InputSystem.Update();
                }

                return;
            }

            // See if we have an axis we can slide a bit.
            for (var i = 0; i < controls.Count; ++i)
            {
                var axis = controls[i] as AxisControl;
                if (axis == null)
                {
                    continue;
                }

                // We do, so nudge its value a bit.
                var           device = axis.device;
                InputEventPtr inputEvent;
                using (StateEvent.From(device, out inputEvent))
                {
                    var currentValue = axis.ReadValue();
                    var newValue     = currentValue + 0.01f;

                    if (axis.clamp && newValue > axis.clampMax)
                    {
                        newValue = axis.clampMin;
                    }

                    axis.WriteValueInto(inputEvent, newValue);
                    InputSystem.QueueEvent(inputEvent);
                    InputSystem.Update();
                }

                return;
            }

            ////TODO: support a wider range of controls
            throw new NotImplementedException();
        }