-
Notifications
You must be signed in to change notification settings - Fork 304
/
InputActionState.cs
4013 lines (3520 loc) · 187 KB
/
InputActionState.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.LowLevel;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.Profiling;
////TODO: now that we can bind to controls by display name, we need to re-resolve controls when those change (e.g. when the keyboard layout changes)
////TODO: remove direct references to InputManager
////TODO: make sure controls in per-action and per-map control arrays are unique (the internal arrays are probably okay to have duplicates)
////REVIEW: should the default interaction be an *explicit* interaction?
////REVIEW: should "pass-through" be an interaction instead of a setting on actions?
////REVIEW: allow setup where state monitor is enabled but action is disabled?
namespace UnityEngine.InputSystem
{
using InputActionListener = Action<InputAction.CallbackContext>;
/// <summary>
/// Dynamic execution state of one or more <see cref="InputActionMap">action maps</see> and
/// all the actions they contain.
/// </summary>
/// <remarks>
/// The aim of this class is to both put all the dynamic execution state into one place as well
/// as to organize state in tight, GC-optimized arrays. Also, by moving state out of individual
/// <see cref="InputActionMap">action maps</see>, we can combine the state of several maps
/// into one single object with a single set of arrays. Ideally, if you have a single action
/// asset in the game, you get a single InputActionState that contains the entire dynamic
/// execution state for your game's actions.
///
/// Note that this class allocates unmanaged memory. It has to be disposed of or it will leak
/// memory!
///
/// An instance of this class is also used for singleton actions by means of the hidden action
/// map we create for those actions. In that case, there will be both a hidden map instance
/// as well as an action state for every separate singleton action. This makes singleton actions
/// relatively expensive.
/// </remarks>
internal unsafe class InputActionState : IInputStateChangeMonitor, ICloneable, IDisposable
{
public const int kInvalidIndex = -1;
/// <summary>
/// Array of all maps added to the state.
/// </summary>
public InputActionMap[] maps;
/// <summary>
/// List of all resolved controls.
/// </summary>
/// <remarks>
/// As we don't know in advance how many controls a binding may match (if any), we bump the size of
/// this array in increments during resolution. This means it may be end up being larger than the total
/// number of used controls and have empty entries at the end. Use <see cref="UnmanagedMemory.controlCount"/> and not
/// <c>.Length</c> to find the actual number of controls.
///
/// All bound controls are included in the array regardless of whether only a partial set of actions
/// is currently enabled. What ultimately decides whether controls get triggered or not is whether we
/// have installed state monitors for them or not.
/// </remarks>
public InputControl[] controls;
/// <summary>
/// Array of instantiated interaction objects.
/// </summary>
/// <remarks>
/// Every binding that has interactions corresponds to a slice of this array.
///
/// Indices match between this and interaction states in <see cref="memory"/>.
/// </remarks>
public IInputInteraction[] interactions;
/// <summary>
/// Processor objects instantiated for the bindings in the state.
/// </summary>
public InputProcessor[] processors;
/// <summary>
/// Array of instantiated composite objects.
/// </summary>
public InputBindingComposite[] composites;
public int totalProcessorCount;
public int totalCompositeCount => memory.compositeCount;
public int totalMapCount => memory.mapCount;
public int totalActionCount => memory.actionCount;
public int totalBindingCount => memory.bindingCount;
public int totalInteractionCount => memory.interactionCount;
public int totalControlCount => memory.controlCount;
/// <summary>
/// Block of unmanaged memory that holds the dynamic execution state of the actions and their controls.
/// </summary>
/// <remarks>
/// We keep several arrays of structured data in a single block of unmanaged memory.
/// </remarks>
public UnmanagedMemory memory;
public ActionMapIndices* mapIndices => memory.mapIndices;
public TriggerState* actionStates => memory.actionStates;
public BindingState* bindingStates => memory.bindingStates;
public InteractionState* interactionStates => memory.interactionStates;
public int* controlIndexToBindingIndex => memory.controlIndexToBindingIndex;
public uint* enabledControls => (uint*)memory.enabledControls;
public bool isProcessingControlStateChange => m_InProcessControlStateChange;
private bool m_OnBeforeUpdateHooked;
private bool m_OnAfterUpdateHooked;
private bool m_InProcessControlStateChange;
private Action m_OnBeforeUpdateDelegate;
private Action m_OnAfterUpdateDelegate;
/// <summary>
/// Initialize execution state with given resolved binding information.
/// </summary>
/// <param name="resolver"></param>
public void Initialize(InputBindingResolver resolver)
{
ClaimDataFrom(resolver);
AddToGlobalList();
}
internal void ClaimDataFrom(InputBindingResolver resolver)
{
totalProcessorCount = resolver.totalProcessorCount;
maps = resolver.maps;
interactions = resolver.interactions;
processors = resolver.processors;
composites = resolver.composites;
controls = resolver.controls;
memory = resolver.memory;
resolver.memory = new UnmanagedMemory();
}
~InputActionState()
{
Destroy(isFinalizing: true);
}
public void Dispose()
{
Destroy();
}
private void Destroy(bool isFinalizing = false)
{
Debug.Assert(!isProcessingControlStateChange, "Must not destroy InputActionState while executing an action callback within it");
if (!isFinalizing)
{
for (var i = 0; i < totalMapCount; ++i)
{
var map = maps[i];
// Remove state change monitors.
if (map.enabled)
DisableControls(i, mapIndices[i].controlStartIndex, mapIndices[i].controlCount);
if (map.m_Asset != null)
map.m_Asset.m_SharedStateForAllMaps = null;
map.m_State = null;
map.m_MapIndexInState = kInvalidIndex;
map.m_EnabledActionsCount = 0;
// Reset action indices on the map's actions.
var actions = map.m_Actions;
if (actions != null)
{
for (var n = 0; n < actions.Length; ++n)
actions[n].m_ActionIndexInState = kInvalidIndex;
}
}
RemoveMapFromGlobalList();
}
memory.Dispose();
}
/// <summary>
/// Create a copy of the state.
/// </summary>
/// <returns></returns>
/// <remarks>
/// The copy is non-functional in so far as it cannot be used to keep track of changes made to
/// any associated actions. However, it can be used to freeze the binding resolution state of
/// a particular set of enabled actions. This is used by <see cref="InputActionTrace"/>.
/// </remarks>
public InputActionState Clone()
{
return new InputActionState
{
maps = ArrayHelpers.Copy(maps),
controls = ArrayHelpers.Copy(controls),
interactions = ArrayHelpers.Copy(interactions),
processors = ArrayHelpers.Copy(processors),
composites = ArrayHelpers.Copy(composites),
totalProcessorCount = totalProcessorCount,
memory = memory.Clone(),
};
}
object ICloneable.Clone()
{
return Clone();
}
/// <summary>
/// Check if the state is currently using a control from the given device.
/// </summary>
/// <param name="device">Any input device.</param>
/// <returns>True if any of the maps in the state has the device in its <see cref="InputActionMap.devices"/>
/// list or if any of the device's controls are contained in <see cref="controls"/>.</returns>
private bool IsUsingDevice(InputDevice device)
{
Debug.Assert(device != null, "Device is null");
// If all maps have device restrictions, the device must be in it
// or we're not using it.
var haveMapsWithoutDeviceRestrictions = false;
for (var i = 0; i < totalMapCount; ++i)
{
var map = maps[i];
var devicesForMap = map.devices;
if (devicesForMap == null)
haveMapsWithoutDeviceRestrictions = true;
else if (devicesForMap.Value.Contains(device))
return true;
}
if (!haveMapsWithoutDeviceRestrictions)
return false;
// Check all our controls one by one.
for (var i = 0; i < totalControlCount; ++i)
if (controls[i].device == device)
return true;
return false;
}
// Check if the state would use a control from the given device.
private bool CanUseDevice(InputDevice device)
{
Debug.Assert(device != null, "Device is null");
// If all maps have device restrictions and the device isn't in them, we can't use
// the device.
var haveMapWithoutDeviceRestrictions = false;
for (var i = 0; i < totalMapCount; ++i)
{
var map = maps[i];
var devicesForMap = map.devices;
if (devicesForMap == null)
haveMapWithoutDeviceRestrictions = true;
else if (devicesForMap.Value.Contains(device))
return true;
}
if (!haveMapWithoutDeviceRestrictions)
return false;
for (var i = 0; i < totalMapCount; ++i)
{
var map = maps[i];
var bindings = map.m_Bindings;
if (bindings == null)
continue;
var bindingCount = bindings.Length;
for (var n = 0; n < bindingCount; ++n)
{
if (InputControlPath.TryFindControl(device, bindings[n].effectivePath) != null)
return true;
}
}
return false;
}
/// <summary>
/// Check whether the state has any actions that are currently enabled.
/// </summary>
/// <returns></returns>
public bool HasEnabledActions()
{
for (var i = 0; i < totalMapCount; ++i)
{
var map = maps[i];
if (map.enabled)
return true;
}
return false;
}
public void FinishBindingCompositeSetups()
{
for (var i = 0; i < totalBindingCount; ++i)
{
ref var binding = ref bindingStates[i];
if (!binding.isComposite || binding.compositeOrCompositeBindingIndex == -1)
continue;
var composite = composites[binding.compositeOrCompositeBindingIndex];
var context = new InputBindingCompositeContext { m_State = this, m_BindingIndex = i };
composite.CallFinishSetup(ref context);
}
}
/// <summary>
/// Synchronize the current action states based on what they were before.
/// </summary>
/// <param name="oldState"></param>
/// <remarks>
/// We do this when we have to temporarily disable actions in order to re-resolve bindings.
///
/// Note that we do NOT restore action states perfectly. I.e. will we will not preserve trigger
/// and interaction states exactly to what they were before. Given that the bound controls may change,
/// it would be non-trivial to reliably correlate the old and the new state. Instead, we simply
/// reenable all the actions and controls that were enabled before and then let the next update
/// take it from there.
/// </remarks>
public void RestoreActionStates(UnmanagedMemory oldState)
{
Debug.Assert(oldState.isAllocated, "Old state contains no memory");
// This method cannot deal with actions and/or maps having been removed.
// It DOES cope with bindings have been added and/or removed, though!
Debug.Assert(oldState.actionCount == memory.actionCount, "Action count in old and new state must be the same");
Debug.Assert(oldState.mapCount == memory.mapCount, "Map count in old and new state must be the same");
// Go through the state map by map and in each map, binding by binding. Enable
// all bound controls for which the respective action isn't disabled.
for (var i = 0; i < memory.bindingCount; ++i)
{
var bindingState = &memory.bindingStates[i];
if (bindingState->isPartOfComposite)
{
// Bindings that are part of composites get enabled through the composite itself.
continue;
}
var actionIndex = bindingState->actionIndex;
if (actionIndex == kInvalidIndex)
{
// Binding is not targeting an action.
continue;
}
// Skip any binding for which the action was disabled.
// NOTE: We check the OLD STATE here. The phase in the new state will change immediately
// on the first binding to an action but there may be multiple bindings leading to the
// same action.
if (oldState.actionStates[actionIndex].phase == InputActionPhase.Disabled)
continue;
// Mark the action as enabled, if not already done.
var actionState = &memory.actionStates[actionIndex];
if (actionState->phase == InputActionPhase.Disabled)
{
actionState->phase = InputActionPhase.Waiting;
// Keep track of actions we enable in each map.
var mapIndex = actionState->mapIndex;
var map = maps[mapIndex];
++map.m_EnabledActionsCount;
}
// Enable all controls on the binding.
EnableControls(actionState->mapIndex, bindingState->controlStartIndex,
bindingState->controlCount);
}
// Make sure we get an initial state check.
HookOnBeforeUpdate();
// Fire notifications.
if (s_GlobalState.onActionChange.length > 0)
{
for (var i = 0; i < totalMapCount; ++i)
{
var map = maps[i];
if (map.m_SingletonAction == null && map.m_EnabledActionsCount == map.m_Actions.LengthSafe())
NotifyListenersOfActionChange(InputActionChange.ActionMapEnabled, map);
else
{
var actions = map.actions;
for (var n = 0; n < actions.Count; ++n)
NotifyListenersOfActionChange(InputActionChange.ActionEnabled, actions[n]);
}
}
}
}
private void ResetActionStatesDrivenBy(InputDevice device)
{
using (InputActionRebindingExtensions.DeferBindingResolution())
{
for (var actionIndex = 0; actionIndex < totalActionCount; ++actionIndex)
{
var actionState = &actionStates[actionIndex];
// Skip actions that aren't in progress.
if (actionState->phase == InputActionPhase.Waiting || actionState->phase == InputActionPhase.Disabled)
continue;
// Skip actions not driven from this device.
if (actionState->isPassThrough)
{
// Pass-through actions are not driven from specific controls yet still benefit
// from being able to observe resets. So for these, we need to check all bound controls,
// not just the one that happen to trigger last.
if (!IsActionBoundToControlFromDevice(device, actionIndex))
continue;
}
else
{
// For button and value actions, we go by whatever is currently driving the action.
var controlIndex = actionState->controlIndex;
if (controlIndex == -1)
continue;
var control = controls[controlIndex];
if (control.device != device)
continue;
}
// Reset.
ResetActionState(actionIndex);
}
}
}
private bool IsActionBoundToControlFromDevice(InputDevice device, int actionIndex)
{
var usesControlFromDevice = false;
var bindingStartIndex = GetActionBindingStartIndexAndCount(actionIndex, out var bindingCount);
for (var i = 0; i < bindingCount; ++i)
{
var bindingIndex = memory.actionBindingIndices[bindingStartIndex + i];
var controlCount = bindingStates[bindingIndex].controlCount;
var controlStartIndex = bindingStates[bindingIndex].controlStartIndex;
for (var n = 0; n < controlCount; ++n)
{
var control = controls[controlStartIndex + n];
if (control.device == device)
{
usesControlFromDevice = true;
break;
}
}
}
return usesControlFromDevice;
}
/// <summary>
/// Reset the trigger state of the given action such that the action has no record of being triggered.
/// </summary>
/// <param name="actionIndex">Action whose state to reset.</param>
/// <param name="toPhase">Phase to reset the action to. Must be either <see cref="InputActionPhase.Waiting"/>
/// or <see cref="InputActionPhase.Disabled"/>. Other phases cannot be transitioned to through resets.</param>
/// <param name="hardReset">If true, also wipe state such as for <see cref="InputAction.WasPressedThisFrame"/> which normally
/// persists even if an action is disabled.</param>
public void ResetActionState(int actionIndex, InputActionPhase toPhase = InputActionPhase.Waiting, bool hardReset = false)
{
Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount, "Action index out of range when resetting action");
Debug.Assert(toPhase == InputActionPhase.Waiting || toPhase == InputActionPhase.Disabled,
"Phase must be Waiting or Disabled");
// If the action in started or performed phase, cancel it first.
var actionState = &actionStates[actionIndex];
if (actionState->phase != InputActionPhase.Waiting && actionState->phase != InputActionPhase.Disabled)
{
// Cancellation calls should receive current time.
actionState->time = InputRuntime.s_Instance.currentTime;
// If the action got triggered from an interaction, go and reset all interactions on the binding
// that got triggered.
if (actionState->interactionIndex != kInvalidIndex)
{
var bindingIndex = actionState->bindingIndex;
if (bindingIndex != kInvalidIndex)
{
var mapIndex = actionState->mapIndex;
var interactionCount = bindingStates[bindingIndex].interactionCount;
var interactionStartIndex = bindingStates[bindingIndex].interactionStartIndex;
for (var i = 0; i < interactionCount; ++i)
{
var interactionIndex = interactionStartIndex + i;
ResetInteractionStateAndCancelIfNecessary(mapIndex, bindingIndex, interactionIndex);
}
}
}
else
{
// No interactions. Cancel the action directly.
Debug.Assert(actionState->bindingIndex != kInvalidIndex, "Binding index on trigger state is invalid");
Debug.Assert(bindingStates[actionState->bindingIndex].interactionCount == 0,
"Action has been triggered but apparently not from an interaction yet there's interactions on the binding that got triggered?!?");
if (actionState->phase != InputActionPhase.Canceled)
ChangePhaseOfAction(InputActionPhase.Canceled, ref actionStates[actionIndex]);
}
}
// Wipe state.
actionState->phase = toPhase;
actionState->controlIndex = kInvalidIndex;
actionState->bindingIndex = 0;
actionState->interactionIndex = kInvalidIndex;
actionState->startTime = 0;
actionState->time = 0;
actionState->hasMultipleConcurrentActuations = false;
actionState->inProcessing = false;
actionState->isPressed = false;
// For "hard resets", wipe state we don't normally wipe. This resets things such as WasPressedThisFrame().
if (hardReset)
{
actionState->lastCanceledInUpdate = default;
actionState->lastPerformedInUpdate = default;
actionState->pressedInUpdate = default;
actionState->releasedInUpdate = default;
}
Debug.Assert(!actionState->isStarted, "Cannot reset an action to started phase");
Debug.Assert(!actionState->isPerformed, "Cannot reset an action to performed phase");
Debug.Assert(!actionState->isCanceled, "Cannot reset an action to canceled phase");
}
public ref TriggerState FetchActionState(InputAction action)
{
Debug.Assert(action != null, "Action must not be null");
Debug.Assert(action.m_ActionMap != null, "Action must have an action map");
Debug.Assert(action.m_ActionMap.m_MapIndexInState != kInvalidIndex, "Action must have index set");
Debug.Assert(maps.Contains(action.m_ActionMap), "Action map must be contained in state");
Debug.Assert(action.m_ActionIndexInState >= 0 && action.m_ActionIndexInState < totalActionCount, "Action index is out of range");
return ref actionStates[action.m_ActionIndexInState];
}
public ActionMapIndices FetchMapIndices(InputActionMap map)
{
Debug.Assert(map != null, "Must must not be null");
Debug.Assert(maps.Contains(map), "Map must be contained in state");
return mapIndices[map.m_MapIndexInState];
}
public void EnableAllActions(InputActionMap map)
{
Debug.Assert(map != null, "Map must not be null");
Debug.Assert(map.m_Actions != null, "Map must have actions");
Debug.Assert(maps.Contains(map), "Map must be contained in state");
// Enable all controls in map that aren't already enabled.
EnableControls(map);
// Put all actions that aren't already enabled into waiting state.
var mapIndex = map.m_MapIndexInState;
Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index on InputActionMap is out of range");
var actionCount = mapIndices[mapIndex].actionCount;
var actionStartIndex = mapIndices[mapIndex].actionStartIndex;
for (var i = 0; i < actionCount; ++i)
{
var actionIndex = actionStartIndex + i;
var actionState = &actionStates[actionIndex];
if (actionState->isDisabled)
actionState->phase = InputActionPhase.Waiting;
actionState->inProcessing = false;
}
map.m_EnabledActionsCount = actionCount;
HookOnBeforeUpdate();
// Make sure that if we happen to get here with one of the hidden action maps we create for singleton
// action, we notify on the action, not the hidden map.
if (map.m_SingletonAction != null)
NotifyListenersOfActionChange(InputActionChange.ActionEnabled, map.m_SingletonAction);
else
NotifyListenersOfActionChange(InputActionChange.ActionMapEnabled, map);
}
private void EnableControls(InputActionMap map)
{
Debug.Assert(map != null, "Map must not be null");
Debug.Assert(map.m_Actions != null, "Map must have actions");
Debug.Assert(maps.Contains(map), "Map must be contained in state");
var mapIndex = map.m_MapIndexInState;
Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index on InputActionMap is out of range");
// Install state monitors for all controls.
var controlCount = mapIndices[mapIndex].controlCount;
var controlStartIndex = mapIndices[mapIndex].controlStartIndex;
if (controlCount > 0)
EnableControls(mapIndex, controlStartIndex, controlCount);
}
public void EnableSingleAction(InputAction action)
{
Debug.Assert(action != null, "Action must not be null");
Debug.Assert(action.m_ActionMap != null, "Action must have action map");
Debug.Assert(maps.Contains(action.m_ActionMap), "Action map must be contained in state");
EnableControls(action);
// Put action into waiting state.
var actionIndex = action.m_ActionIndexInState;
Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount,
"Action index out of range when enabling single action");
actionStates[actionIndex].phase = InputActionPhase.Waiting;
++action.m_ActionMap.m_EnabledActionsCount;
HookOnBeforeUpdate();
NotifyListenersOfActionChange(InputActionChange.ActionEnabled, action);
}
private void EnableControls(InputAction action)
{
Debug.Assert(action != null, "Action must not be null");
Debug.Assert(action.m_ActionMap != null, "Action must have action map");
Debug.Assert(maps.Contains(action.m_ActionMap), "Map must be contained in state");
var actionIndex = action.m_ActionIndexInState;
Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount,
"Action index out of range when enabling controls");
var map = action.m_ActionMap;
var mapIndex = map.m_MapIndexInState;
Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index out of range in EnableControls");
// Go through all bindings in the map and for all that belong to the given action,
// enable the associated controls.
var bindingStartIndex = mapIndices[mapIndex].bindingStartIndex;
var bindingCount = mapIndices[mapIndex].bindingCount;
var bindingStatesPtr = memory.bindingStates;
for (var i = 0; i < bindingCount; ++i)
{
var bindingIndex = bindingStartIndex + i;
var bindingState = &bindingStatesPtr[bindingIndex];
if (bindingState->actionIndex != actionIndex)
continue;
// Composites enable en-bloc through the composite binding itself.
if (bindingState->isPartOfComposite)
continue;
var controlCount = bindingState->controlCount;
if (controlCount == 0)
continue;
EnableControls(mapIndex, bindingState->controlStartIndex, controlCount);
}
}
public void DisableAllActions(InputActionMap map)
{
Debug.Assert(map != null, "Map must not be null");
Debug.Assert(map.m_Actions != null, "Map must have actions");
Debug.Assert(maps.Contains(map), "Map must be contained in state");
DisableControls(map);
// Mark all actions as disabled.
var mapIndex = map.m_MapIndexInState;
Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index out of range in DisableAllActions");
var actionStartIndex = mapIndices[mapIndex].actionStartIndex;
var actionCount = mapIndices[mapIndex].actionCount;
for (var i = 0; i < actionCount; ++i)
{
var actionIndex = actionStartIndex + i;
if (actionStates[actionIndex].phase != InputActionPhase.Disabled)
ResetActionState(actionIndex, toPhase: InputActionPhase.Disabled);
}
map.m_EnabledActionsCount = 0;
// Make sure that if we happen to get here with one of the hidden action maps we create for singleton
// action, we notify on the action, not the hidden map.
if (map.m_SingletonAction != null)
NotifyListenersOfActionChange(InputActionChange.ActionDisabled, map.m_SingletonAction);
else
NotifyListenersOfActionChange(InputActionChange.ActionMapDisabled, map);
}
private void DisableControls(InputActionMap map)
{
Debug.Assert(map != null, "Map must not be null");
Debug.Assert(map.m_Actions != null, "Map must have actions");
Debug.Assert(maps.Contains(map), "Map must be contained in state");
var mapIndex = map.m_MapIndexInState;
Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index out of range in DisableControls(InputActionMap)");
// Remove state monitors from all controls.
var controlCount = mapIndices[mapIndex].controlCount;
var controlStartIndex = mapIndices[mapIndex].controlStartIndex;
if (controlCount > 0)
DisableControls(mapIndex, controlStartIndex, controlCount);
}
public void DisableSingleAction(InputAction action)
{
Debug.Assert(action != null, "Action must not be null");
Debug.Assert(action.m_ActionMap != null, "Action must have action map");
Debug.Assert(maps.Contains(action.m_ActionMap), "Action map must be contained in state");
DisableControls(action);
ResetActionState(action.m_ActionIndexInState, toPhase: InputActionPhase.Disabled);
--action.m_ActionMap.m_EnabledActionsCount;
NotifyListenersOfActionChange(InputActionChange.ActionDisabled, action);
}
private void DisableControls(InputAction action)
{
Debug.Assert(action != null, "Action must not be null");
Debug.Assert(action.m_ActionMap != null, "Action must have action map");
Debug.Assert(maps.Contains(action.m_ActionMap), "Action map must be contained in state");
var actionIndex = action.m_ActionIndexInState;
Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount,
"Action index out of range when disabling controls");
var map = action.m_ActionMap;
var mapIndex = map.m_MapIndexInState;
Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index out of range in DisableControls(InputAction)");
// Go through all bindings in the map and for all that belong to the given action,
// disable the associated controls.
var bindingStartIndex = mapIndices[mapIndex].bindingStartIndex;
var bindingCount = mapIndices[mapIndex].bindingCount;
var bindingStatesPtr = memory.bindingStates;
for (var i = 0; i < bindingCount; ++i)
{
var bindingIndex = bindingStartIndex + i;
var bindingState = &bindingStatesPtr[bindingIndex];
if (bindingState->actionIndex != actionIndex)
continue;
// Composites enable en-bloc through the composite binding itself.
if (bindingState->isPartOfComposite)
continue;
var controlCount = bindingState->controlCount;
if (controlCount == 0)
continue;
DisableControls(mapIndex, bindingState->controlStartIndex, controlCount);
}
}
////REVIEW: can we have a method on InputManager doing this in bulk?
////NOTE: This must not enable only a partial set of controls on a binding (currently we have no setup that would lead to that)
private void EnableControls(int mapIndex, int controlStartIndex, int numControls)
{
Debug.Assert(controls != null, "State must have controls");
Debug.Assert(controlStartIndex >= 0 && (controlStartIndex < totalControlCount || numControls == 0),
"Control start index out of range");
Debug.Assert(controlStartIndex + numControls <= totalControlCount, "Control range out of bounds");
var manager = InputSystem.s_Manager;
for (var i = 0; i < numControls; ++i)
{
var controlIndex = controlStartIndex + i;
// We don't want to add multiple state monitors for the same control. This can happen if enabling
// single actions is mixed with enabling actions maps containing them.
if (IsControlEnabled(controlIndex))
continue;
var bindingIndex = controlIndexToBindingIndex[controlIndex];
var mapControlAndBindingIndex = ToCombinedMapAndControlAndBindingIndex(mapIndex, controlIndex, bindingIndex);
var bindingStatePtr = &bindingStates[bindingIndex];
if (bindingStatePtr->wantsInitialStateCheck)
SetInitialStateCheckPending(bindingStatePtr, true);
manager.AddStateChangeMonitor(controls[controlIndex], this, mapControlAndBindingIndex);
SetControlEnabled(controlIndex, true);
}
}
private void DisableControls(int mapIndex, int controlStartIndex, int numControls)
{
Debug.Assert(controls != null, "State must have controls");
Debug.Assert(controlStartIndex >= 0 && (controlStartIndex < totalControlCount || numControls == 0),
"Control start index out of range");
Debug.Assert(controlStartIndex + numControls <= totalControlCount, "Control range out of bounds");
var manager = InputSystem.s_Manager;
for (var i = 0; i < numControls; ++i)
{
var controlIndex = controlStartIndex + i;
if (!IsControlEnabled(controlIndex))
continue;
var bindingIndex = controlIndexToBindingIndex[controlIndex];
var mapControlAndBindingIndex = ToCombinedMapAndControlAndBindingIndex(mapIndex, controlIndex, bindingIndex);
var bindingStatePtr = &bindingStates[bindingIndex];
if (bindingStatePtr->wantsInitialStateCheck)
SetInitialStateCheckPending(bindingStatePtr, false);
manager.RemoveStateChangeMonitor(controls[controlIndex], this, mapControlAndBindingIndex);
SetControlEnabled(controlIndex, false);
}
}
private void SetInitialStateCheckPending(BindingState* bindingStatePtr, bool value)
{
if (bindingStatePtr->isPartOfComposite)
{
// For composites, we always flag the composite itself as wanting an initial state check. This
// way, we don't have to worry about triggering the composite multiple times when several of its
// controls are actuated.
var compositeIndex = bindingStatePtr->compositeOrCompositeBindingIndex;
bindingStates[compositeIndex].initialStateCheckPending = value;
}
else
{
bindingStatePtr->initialStateCheckPending = value;
}
}
private bool IsControlEnabled(int controlIndex)
{
var intIndex = controlIndex / 32;
var mask = 1U << (controlIndex % 32);
return (enabledControls[intIndex] & mask) != 0;
}
private void SetControlEnabled(int controlIndex, bool state)
{
var intIndex = controlIndex / 32;
var mask = 1U << (controlIndex % 32);
if (state)
enabledControls[intIndex] |= mask;
else
enabledControls[intIndex] &= ~mask;
}
private void HookOnBeforeUpdate()
{
if (m_OnBeforeUpdateHooked)
return;
if (m_OnBeforeUpdateDelegate == null)
m_OnBeforeUpdateDelegate = OnBeforeInitialUpdate;
InputSystem.s_Manager.onBeforeUpdate += m_OnBeforeUpdateDelegate;
m_OnBeforeUpdateHooked = true;
}
private void UnhookOnBeforeUpdate()
{
if (!m_OnBeforeUpdateHooked)
return;
InputSystem.s_Manager.onBeforeUpdate -= m_OnBeforeUpdateDelegate;
m_OnBeforeUpdateHooked = false;
}
// We hook this into InputManager.onBeforeUpdate every time actions are enabled and then take it off
// the list after the first call. Inside here we check whether any actions we enabled already have
// non-default state on bound controls.
//
// NOTE: We do this as a callback from onBeforeUpdate rather than directly when the action is enabled
// to ensure that the callbacks happen during input processing and not randomly from wherever
// an action happens to be enabled.
private void OnBeforeInitialUpdate()
{
if (InputState.currentUpdateType == InputUpdateType.BeforeRender
#if UNITY_EDITOR
|| InputState.currentUpdateType == InputUpdateType.Editor
#endif
)
return;
// Remove us from the callback as the processing we're doing here is a one-time thing.
UnhookOnBeforeUpdate();
Profiler.BeginSample("InitialActionStateCheck");
// Use current time as time of control state change.
var time = InputRuntime.s_Instance.currentTime;
////REVIEW: should we store this data in a separate place rather than go through all bindingStates?
// Go through all binding states and for every binding that needs an initial state check,
// go through all bound controls and for each one that isn't in its default state, pretend
// that the control just got actuated.
for (var bindingIndex = 0; bindingIndex < totalBindingCount; ++bindingIndex)
{
var bindingStatePtr = &bindingStates[bindingIndex];
if (!bindingStatePtr->initialStateCheckPending)
continue;
Debug.Assert(!bindingStatePtr->isPartOfComposite, "Initial state check flag must be set on composite, not on its parts");
bindingStatePtr->initialStateCheckPending = false;
var mapIndex = bindingStatePtr->mapIndex;
var controlStartIndex = bindingStatePtr->controlStartIndex;
var controlCount = bindingStatePtr->controlCount;
var isComposite = bindingStatePtr->isComposite;
for (var n = 0; n < controlCount; ++n)
{
var controlIndex = controlStartIndex + n;
var control = controls[controlIndex];
if (!control.CheckStateIsAtDefault())
{
// For composites, the binding index we have at this point is for the composite binding, not for the part
// binding that contributes the control we're looking at. Adjust for that.
var bindingIndexForControl = bindingIndex;
if (isComposite)
bindingIndexForControl = controlIndexToBindingIndex[controlIndex];
ProcessControlStateChange(mapIndex, controlIndex, bindingIndexForControl, time, default);
// For composites, any one actuated control will lead to the composite being
// processed as a whole so we can stop here. This also ensure that we are
// not triggering the composite repeatedly if there are multiple actuated
// controls bound to its parts.
if (isComposite)
break;
}
}
}
Profiler.EndSample();
}
// Called from InputManager when one of our state change monitors has fired.
// Tells us the time of the change *according to the state events coming in*.
// Also tells us which control of the controls we are binding to triggered the
// change and relays the binding index we gave it when we called AddChangeMonitor.
void IInputStateChangeMonitor.NotifyControlStateChanged(InputControl control, double time,
InputEventPtr eventPtr, long mapControlAndBindingIndex)
{
#if UNITY_EDITOR
if (InputState.currentUpdateType == InputUpdateType.Editor)
return;
#endif
SplitUpMapAndControlAndBindingIndex(mapControlAndBindingIndex, out var mapIndex, out var controlIndex, out var bindingIndex);
ProcessControlStateChange(mapIndex, controlIndex, bindingIndex, time, eventPtr);
}
void IInputStateChangeMonitor.NotifyTimerExpired(InputControl control, double time,
long mapControlAndBindingIndex, int interactionIndex)
{
SplitUpMapAndControlAndBindingIndex(mapControlAndBindingIndex, out var mapIndex, out var controlIndex, out var bindingIndex);
ProcessTimeout(time, mapIndex, controlIndex, bindingIndex, interactionIndex);
}
// We mangle the various indices we use into a single long for association with state change
// monitors. While we could look up map and binding indices from control indices, keeping
// all the information together avoids having to unnecessarily jump around in memory to grab
// the various pieces of data.
private static long ToCombinedMapAndControlAndBindingIndex(int mapIndex, int controlIndex, int bindingIndex)
{
var result = (long)controlIndex;
result |= (long)bindingIndex << 32;
result |= (long)mapIndex << 48;
return result;
}
private static void SplitUpMapAndControlAndBindingIndex(long mapControlAndBindingIndex, out int mapIndex,
out int controlIndex, out int bindingIndex)
{
controlIndex = (int)(mapControlAndBindingIndex & 0xffffffff);
bindingIndex = (int)((mapControlAndBindingIndex >> 32) & 0xffff);
mapIndex = (int)(mapControlAndBindingIndex >> 48);
}
/// <summary>
/// Process a state change that has happened in one of the controls attached
/// to this action map state.
/// </summary>
/// <param name="mapIndex">Index of the action map to which the binding belongs.</param>