-
Notifications
You must be signed in to change notification settings - Fork 324
/
Copy pathInputManager.cs
4328 lines (3730 loc) · 200 KB
/
InputManager.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.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using Unity.Collections;
using UnityEngine.InputSystem.Composites;
using UnityEngine.InputSystem.Controls;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.InputSystem.LowLevel;
using UnityEngine.InputSystem.Processors;
using UnityEngine.InputSystem.Interactions;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.InputSystem.Layouts;
using Unity.Profiling;
#if UNITY_EDITOR
using UnityEngine.InputSystem.Editor;
#endif
#if UNITY_EDITOR
using CustomBindingPathValidator = System.Func<string, System.Action>;
#endif
////TODO: make diagnostics available in dev players and give it a public API to enable them
////TODO: work towards InputManager having no direct knowledge of actions
////TODO: allow pushing events into the system any which way; decouple from the buffer in NativeInputSystem being the only source
////REVIEW: change the event properties over to using IObservable?
////REVIEW: instead of RegisterInteraction and RegisterProcessor, have a generic RegisterInterface (or something)?
////REVIEW: can we do away with the 'previous == previous frame' and simply buffer flip on every value write?
////REVIEW: should we force keeping mouse/pen/keyboard/touch around in editor even if not in list of supported devices?
////REVIEW: do we want to filter out state events that result in no state change?
#pragma warning disable CS0649
namespace UnityEngine.InputSystem
{
using DeviceChangeListener = Action<InputDevice, InputDeviceChange>;
using DeviceStateChangeListener = Action<InputDevice, InputEventPtr>;
using LayoutChangeListener = Action<string, InputControlLayoutChange>;
using EventListener = Action<InputEventPtr, InputDevice>;
using UpdateListener = Action;
/// <summary>
/// Hub of the input system.
/// </summary>
/// <remarks>
/// Not exposed. Use <see cref="InputSystem"/> as the public entry point to the system.
///
/// Manages devices, layouts, and event processing.
/// </remarks>
internal partial class InputManager
{
public ReadOnlyArray<InputDevice> devices => new ReadOnlyArray<InputDevice>(m_Devices, 0, m_DevicesCount);
public TypeTable processors => m_Processors;
public TypeTable interactions => m_Interactions;
public TypeTable composites => m_Composites;
static readonly ProfilerMarker k_InputUpdateProfilerMarker = new ProfilerMarker("InputUpdate");
static readonly ProfilerMarker k_InputTryFindMatchingControllerMarker = new ProfilerMarker("InputSystem.TryFindMatchingControlLayout");
static readonly ProfilerMarker k_InputAddDeviceMarker = new ProfilerMarker("InputSystem.AddDevice");
static readonly ProfilerMarker k_InputRestoreDevicesAfterReloadMarker = new ProfilerMarker("InputManager.RestoreDevicesAfterDomainReload");
static readonly ProfilerMarker k_InputRegisterCustomTypesMarker = new ProfilerMarker("InputManager.RegisterCustomTypes");
static readonly ProfilerMarker k_InputOnBeforeUpdateMarker = new ProfilerMarker("InputSystem.onBeforeUpdate");
static readonly ProfilerMarker k_InputOnAfterUpdateMarker = new ProfilerMarker("InputSystem.onAfterUpdate");
static readonly ProfilerMarker k_InputOnSettingsChangeMarker = new ProfilerMarker("InputSystem.onSettingsChange");
static readonly ProfilerMarker k_InputOnDeviceSettingsChangeMarker = new ProfilerMarker("InputSystem.onDeviceSettingsChange");
static readonly ProfilerMarker k_InputOnEventMarker = new ProfilerMarker("InputSystem.onEvent");
static readonly ProfilerMarker k_InputOnLayoutChangeMarker = new ProfilerMarker("InputSystem.onLayoutChange");
static readonly ProfilerMarker k_InputOnDeviceChangeMarker = new ProfilerMarker("InpustSystem.onDeviceChange");
static readonly ProfilerMarker k_InputOnActionsChangeMarker = new ProfilerMarker("InpustSystem.onActionsChange");
private int CountControls()
{
var count = m_DevicesCount;
for (var i = 0; i < m_DevicesCount; ++i)
count += m_Devices[i].allControls.Count;
return count;
}
public InputMetrics metrics
{
get
{
var result = m_Metrics;
result.currentNumDevices = m_DevicesCount;
result.currentStateSizeInBytes = (int)m_StateBuffers.totalSize;
result.currentControlCount = CountControls();
// Count layouts.
result.currentLayoutCount = m_Layouts.layoutTypes.Count;
result.currentLayoutCount += m_Layouts.layoutStrings.Count;
result.currentLayoutCount += m_Layouts.layoutBuilders.Count;
result.currentLayoutCount += m_Layouts.layoutOverrides.Count;
return result;
}
}
public InputSettings settings
{
get
{
Debug.Assert(m_Settings != null);
return m_Settings;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (m_Settings == value)
return;
m_Settings = value;
ApplySettings();
}
}
#if UNITY_INPUT_SYSTEM_PROJECT_WIDE_ACTIONS
public InputActionAsset actions
{
get
{
return m_Actions;
}
set
{
m_Actions = value;
ApplyActions();
}
}
#endif
public InputUpdateType updateMask
{
get => m_UpdateMask;
set
{
// In editor, we don't allow disabling editor updates.
#if UNITY_EDITOR
value |= InputUpdateType.Editor;
#endif
if (m_UpdateMask == value)
return;
m_UpdateMask = value;
// Recreate state buffers.
if (m_DevicesCount > 0)
ReallocateStateBuffers();
}
}
public InputUpdateType defaultUpdateType
{
get
{
if (m_CurrentUpdate != default)
return m_CurrentUpdate;
#if UNITY_EDITOR
if (!m_RunPlayerUpdatesInEditMode && (!gameIsPlaying || !gameHasFocus))
return InputUpdateType.Editor;
#endif
return m_UpdateMask.GetUpdateTypeForPlayer();
}
}
public InputSettings.ScrollDeltaBehavior scrollDeltaBehavior
{
get => m_ScrollDeltaBehavior;
set
{
if (m_ScrollDeltaBehavior == value)
return;
m_ScrollDeltaBehavior = value;
#if UNITY_INPUT_SYSTEM_PLATFORM_SCROLL_DELTA
InputRuntime.s_Instance.normalizeScrollWheelDelta =
m_ScrollDeltaBehavior == InputSettings.ScrollDeltaBehavior.UniformAcrossAllPlatforms;
#endif
}
}
public float pollingFrequency
{
get => m_PollingFrequency;
set
{
////REVIEW: allow setting to zero to turn off polling altogether?
if (value <= 0)
throw new ArgumentException("Polling frequency must be greater than zero", "value");
m_PollingFrequency = value;
if (m_Runtime != null)
m_Runtime.pollingFrequency = value;
}
}
public event DeviceChangeListener onDeviceChange
{
add => m_DeviceChangeListeners.AddCallback(value);
remove => m_DeviceChangeListeners.RemoveCallback(value);
}
public event DeviceStateChangeListener onDeviceStateChange
{
add => m_DeviceStateChangeListeners.AddCallback(value);
remove => m_DeviceStateChangeListeners.RemoveCallback(value);
}
public event InputDeviceCommandDelegate onDeviceCommand
{
add => m_DeviceCommandCallbacks.AddCallback(value);
remove => m_DeviceCommandCallbacks.RemoveCallback(value);
}
////REVIEW: would be great to have a way to sort out precedence between two callbacks
public event InputDeviceFindControlLayoutDelegate onFindControlLayoutForDevice
{
add
{
m_DeviceFindLayoutCallbacks.AddCallback(value);
// Having a new callback on this event can change the set of devices we recognize.
// See if there's anything in the list of available devices that we can now turn
// into an InputDevice whereas we couldn't before.
//
// NOTE: A callback could also impact already existing devices and theoretically alter
// what layout we would have used for those. We do *NOT* retroactively apply
// those changes.
AddAvailableDevicesThatAreNowRecognized();
}
remove => m_DeviceFindLayoutCallbacks.RemoveCallback(value);
}
public event LayoutChangeListener onLayoutChange
{
add => m_LayoutChangeListeners.AddCallback(value);
remove => m_LayoutChangeListeners.RemoveCallback(value);
}
////TODO: add InputEventBuffer struct that uses NativeArray underneath
////TODO: make InputEventTrace use NativeArray
////TODO: introduce an alternative that consumes events in bulk
public event EventListener onEvent
{
add => m_EventListeners.AddCallback(value);
remove => m_EventListeners.RemoveCallback(value);
}
public event UpdateListener onBeforeUpdate
{
add
{
InstallBeforeUpdateHookIfNecessary();
m_BeforeUpdateListeners.AddCallback(value);
}
remove => m_BeforeUpdateListeners.RemoveCallback(value);
}
public event UpdateListener onAfterUpdate
{
add => m_AfterUpdateListeners.AddCallback(value);
remove => m_AfterUpdateListeners.RemoveCallback(value);
}
public event Action onSettingsChange
{
add => m_SettingsChangedListeners.AddCallback(value);
remove => m_SettingsChangedListeners.RemoveCallback(value);
}
#if UNITY_INPUT_SYSTEM_PROJECT_WIDE_ACTIONS
public event Action onActionsChange
{
add => m_ActionsChangedListeners.AddCallback(value);
remove => m_ActionsChangedListeners.RemoveCallback(value);
}
#endif
public bool isProcessingEvents => m_InputEventStream.isOpen;
#if UNITY_EDITOR
/// <summary>
/// Callback that can be used to display a warning and draw additional custom Editor UI for bindings.
/// </summary>
/// <seealso cref="InputSystem.customBindingPathValidators"/>
/// <remarks>
/// This is not intended to be called directly.
/// Please use <see cref="InputSystem.customBindingPathValidators"/> instead.
/// </remarks>
internal event CustomBindingPathValidator customBindingPathValidators
{
add => m_customBindingPathValidators.AddCallback(value);
remove => m_customBindingPathValidators.RemoveCallback(value);
}
/// <summary>
/// Invokes any custom UI rendering code for this Binding Path in the editor.
/// </summary>
/// <seealso cref="InputSystem.customBindingPathValidators"/>
/// <remarks>
/// This is not intended to be called directly.
/// Please use <see cref="InputSystem.OnDrawCustomWarningForBindingPath"/> instead.
/// </remarks>
internal void OnDrawCustomWarningForBindingPath(string bindingPath)
{
DelegateHelpers.InvokeCallbacksSafe_AndInvokeReturnedActions(
ref m_customBindingPathValidators,
bindingPath,
"InputSystem.OnDrawCustomWarningForBindingPath");
}
/// <summary>
/// Determines if any warning icon is to be displayed for this Binding Path in the editor.
/// </summary>
/// <seealso cref="InputSystem.customBindingPathValidators"/>
/// <remarks>
/// This is not intended to be called directly.
/// Please use <see cref="InputSystem.OnDrawCustomWarningForBindingPath"/> instead.
/// </remarks>
internal bool ShouldDrawWarningIconForBinding(string bindingPath)
{
return DelegateHelpers.InvokeCallbacksSafe_AnyCallbackReturnsObject(
ref m_customBindingPathValidators,
bindingPath,
"InputSystem.ShouldDrawWarningIconForBinding");
}
#endif // UNITY_EDITOR
#if UNITY_EDITOR
private bool m_RunPlayerUpdatesInEditMode;
/// <summary>
/// If true, consider the editor to be in "perpetual play mode". Meaning, we ignore editor
/// updates and just go and continuously process Dynamic/Fixed/BeforeRender regardless of
/// whether we're in play mode or not.
///
/// In this mode, we also ignore game view focus.
/// </summary>
public bool runPlayerUpdatesInEditMode
{
get => m_RunPlayerUpdatesInEditMode;
set => m_RunPlayerUpdatesInEditMode = value;
}
#endif
private bool gameIsPlaying =>
#if UNITY_EDITOR
(m_Runtime.isInPlayMode && !m_Runtime.isPaused) || m_RunPlayerUpdatesInEditMode;
#else
true;
#endif
private bool gameHasFocus =>
#if UNITY_EDITOR
m_RunPlayerUpdatesInEditMode || m_HasFocus || gameShouldGetInputRegardlessOfFocus;
#else
m_HasFocus || gameShouldGetInputRegardlessOfFocus;
#endif
private bool gameShouldGetInputRegardlessOfFocus =>
m_Settings.backgroundBehavior == InputSettings.BackgroundBehavior.IgnoreFocus
#if UNITY_EDITOR
&& m_Settings.editorInputBehaviorInPlayMode == InputSettings.EditorInputBehaviorInPlayMode.AllDeviceInputAlwaysGoesToGameView
#endif
;
////TODO: when registering a layout that exists as a layout of a different type (type vs string vs constructor),
//// remove the existing registration
// Add a layout constructed from a type.
// If a layout with the same name already exists, the new layout
// takes its place.
public void RegisterControlLayout(string name, Type type)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(name));
if (type == null)
throw new ArgumentNullException(nameof(type));
// Note that since InputDevice derives from InputControl, isDeviceLayout implies
// isControlLayout to be true as well.
var isDeviceLayout = typeof(InputDevice).IsAssignableFrom(type);
var isControlLayout = typeof(InputControl).IsAssignableFrom(type);
if (!isDeviceLayout && !isControlLayout)
throw new ArgumentException($"Types used as layouts have to be InputControls or InputDevices; '{type.Name}' is a '{type.BaseType.Name}'",
nameof(type));
var internedName = new InternedString(name);
var isReplacement = m_Layouts.HasLayout(internedName);
// All we do is enter the type into a map. We don't construct an InputControlLayout
// from it until we actually need it in an InputDeviceBuilder to create a device.
// This not only avoids us creating a bunch of objects on the managed heap but
// also avoids us laboriously constructing a XRController layout, for example,
// in a game that never uses XR.
m_Layouts.layoutTypes[internedName] = type;
////TODO: make this independent of initialization order
////TODO: re-scan base type information after domain reloads
// Walk class hierarchy all the way up to InputControl to see
// if there's another type that's been registered as a layout.
// If so, make it a base layout for this one.
string baseLayout = null;
for (var baseType = type.BaseType; baseLayout == null && baseType != typeof(InputControl);
baseType = baseType.BaseType)
{
foreach (var entry in m_Layouts.layoutTypes)
if (entry.Value == baseType)
{
baseLayout = entry.Key;
break;
}
}
PerformLayoutPostRegistration(internedName, new InlinedArray<InternedString>(new InternedString(baseLayout)),
isReplacement, isKnownToBeDeviceLayout: isDeviceLayout);
}
public void RegisterControlLayout(string json, string name = null, bool isOverride = false)
{
if (string.IsNullOrEmpty(json))
throw new ArgumentNullException(nameof(json));
////REVIEW: as long as no one has instantiated the layout, the base layout information is kinda pointless
// Parse out name, device description, and base layout.
InputControlLayout.ParseHeaderFieldsFromJson(json, out var nameFromJson, out var baseLayouts,
out var deviceMatcher);
// Decide whether to take name from JSON or from code.
var internedLayoutName = new InternedString(name);
if (internedLayoutName.IsEmpty())
{
internedLayoutName = nameFromJson;
// Make sure we have a name.
if (internedLayoutName.IsEmpty())
throw new ArgumentException("Layout name has not been given and is not set in JSON layout",
nameof(name));
}
// If it's an override, it must have a layout the overrides apply to.
if (isOverride && baseLayouts.length == 0)
{
throw new ArgumentException(
$"Layout override '{internedLayoutName}' must have 'extend' property mentioning layout to which to apply the overrides",
nameof(json));
}
// Add it to our records.
var isReplacement = m_Layouts.HasLayout(internedLayoutName);
if (isReplacement && isOverride)
{ // Do not allow a layout override to replace a "base layout" by name, but allow layout overrides
// to replace an existing layout override.
// This is required to guarantee that its a hierarchy (directed graph) rather
// than a cyclic graph.
var isReplacingOverride = m_Layouts.layoutOverrideNames.Contains(internedLayoutName);
if (!isReplacingOverride)
{
throw new ArgumentException($"Failed to register layout override '{internedLayoutName}'" +
$"since a layout named '{internedLayoutName}' already exist. Layout overrides must " +
$"have unique names with respect to existing layouts.");
}
}
m_Layouts.layoutStrings[internedLayoutName] = json;
if (isOverride)
{
m_Layouts.layoutOverrideNames.Add(internedLayoutName);
for (var i = 0; i < baseLayouts.length; ++i)
{
var baseLayoutName = baseLayouts[i];
m_Layouts.layoutOverrides.TryGetValue(baseLayoutName, out var overrideList);
if (!isReplacement)
ArrayHelpers.Append(ref overrideList, internedLayoutName);
m_Layouts.layoutOverrides[baseLayoutName] = overrideList;
}
}
PerformLayoutPostRegistration(internedLayoutName, baseLayouts,
isReplacement: isReplacement, isOverride: isOverride);
// If the layout contained a device matcher, register it.
if (!deviceMatcher.empty)
RegisterControlLayoutMatcher(internedLayoutName, deviceMatcher);
}
public void RegisterControlLayoutBuilder(Func<InputControlLayout> method, string name,
string baseLayout = null)
{
if (method == null)
throw new ArgumentNullException(nameof(method));
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(name));
var internedLayoutName = new InternedString(name);
var internedBaseLayoutName = new InternedString(baseLayout);
var isReplacement = m_Layouts.HasLayout(internedLayoutName);
m_Layouts.layoutBuilders[internedLayoutName] = method;
PerformLayoutPostRegistration(internedLayoutName, new InlinedArray<InternedString>(internedBaseLayoutName),
isReplacement);
}
private void PerformLayoutPostRegistration(InternedString layoutName, InlinedArray<InternedString> baseLayouts,
bool isReplacement, bool isKnownToBeDeviceLayout = false, bool isOverride = false)
{
++m_LayoutRegistrationVersion;
// Force-clear layout cache. Don't clear reference count so that
// the cache gets cleared out properly when released in case someone
// is using it ATM.
InputControlLayout.s_CacheInstance.Clear();
// For layouts that aren't overrides, add the name of the base
// layout to the lookup table.
if (!isOverride && baseLayouts.length > 0)
{
if (baseLayouts.length > 1)
throw new NotSupportedException(
$"Layout '{layoutName}' has multiple base layouts; this is only supported on layout overrides");
var baseLayoutName = baseLayouts[0];
if (!baseLayoutName.IsEmpty())
m_Layouts.baseLayoutTable[layoutName] = baseLayoutName;
}
// Nuke any precompiled layouts that are invalidated by the layout registration.
m_Layouts.precompiledLayouts.Remove(layoutName);
if (m_Layouts.precompiledLayouts.Count > 0)
{
foreach (var layout in m_Layouts.precompiledLayouts.Keys.ToArray())
{
var metadata = m_Layouts.precompiledLayouts[layout].metadata;
// If it's an override, we remove any precompiled layouts to which overrides are applied.
if (isOverride)
{
for (var i = 0; i < baseLayouts.length; ++i)
if (layout == baseLayouts[i] ||
StringHelpers.CharacterSeparatedListsHaveAtLeastOneCommonElement(metadata,
baseLayouts[i], ';'))
m_Layouts.precompiledLayouts.Remove(layout);
}
else
{
// Otherwise, we remove any precompile layouts that use the layout we just changed.
if (StringHelpers.CharacterSeparatedListsHaveAtLeastOneCommonElement(metadata,
layoutName, ';'))
m_Layouts.precompiledLayouts.Remove(layout);
}
}
}
// Recreate any devices using the layout. If it's an override, recreate devices using any of the base layouts.
if (isOverride)
{
for (var i = 0; i < baseLayouts.length; ++i)
RecreateDevicesUsingLayout(baseLayouts[i], isKnownToBeDeviceLayout: isKnownToBeDeviceLayout);
}
else
{
RecreateDevicesUsingLayout(layoutName, isKnownToBeDeviceLayout: isKnownToBeDeviceLayout);
}
// In the editor, layouts may become available successively after a domain reload so
// we may end up retaining device information all the way until we run the first full
// player update. For every layout we register, we check here whether we have a saved
// device state using a layout with the same name but not having a device description
// (the latter is important as in that case, we should go through the normal matching
// process and not just rely on the name of the layout). If so, we try here to recreate
// the device with the just registered layout.
#if UNITY_EDITOR
for (var i = 0; i < m_SavedDeviceStates.LengthSafe(); ++i)
{
ref var deviceState = ref m_SavedDeviceStates[i];
if (layoutName != deviceState.layout || !deviceState.description.empty)
continue;
if (RestoreDeviceFromSavedState(ref deviceState, layoutName))
{
ArrayHelpers.EraseAt(ref m_SavedDeviceStates, i);
--i;
}
}
#endif
// Let listeners know.
var change = isReplacement ? InputControlLayoutChange.Replaced : InputControlLayoutChange.Added;
DelegateHelpers.InvokeCallbacksSafe(ref m_LayoutChangeListeners, layoutName.ToString(), change, k_InputOnLayoutChangeMarker, "InputSystem.onLayoutChange");
}
public void RegisterPrecompiledLayout<TDevice>(string metadata)
where TDevice : InputDevice, new()
{
if (metadata == null)
throw new ArgumentNullException(nameof(metadata));
var deviceType = typeof(TDevice).BaseType;
var layoutName = FindOrRegisterDeviceLayoutForType(deviceType);
m_Layouts.precompiledLayouts[layoutName] = new InputControlLayout.Collection.PrecompiledLayout
{
factoryMethod = () => new TDevice(),
metadata = metadata
};
}
private void RecreateDevicesUsingLayout(InternedString layout, bool isKnownToBeDeviceLayout = false)
{
if (m_DevicesCount == 0)
return;
List<InputDevice> devicesUsingLayout = null;
// Find all devices using the layout.
for (var i = 0; i < m_DevicesCount; ++i)
{
var device = m_Devices[i];
bool usesLayout;
if (isKnownToBeDeviceLayout)
usesLayout = IsControlUsingLayout(device, layout);
else
usesLayout = IsControlOrChildUsingLayoutRecursive(device, layout);
if (usesLayout)
{
if (devicesUsingLayout == null)
devicesUsingLayout = new List<InputDevice>();
devicesUsingLayout.Add(device);
}
}
// If there's none, we're good.
if (devicesUsingLayout == null)
return;
// Remove and re-add the matching devices.
using (InputDeviceBuilder.Ref())
{
for (var i = 0; i < devicesUsingLayout.Count; ++i)
{
var device = devicesUsingLayout[i];
RecreateDevice(device, device.m_Layout);
}
}
}
private bool IsControlOrChildUsingLayoutRecursive(InputControl control, InternedString layout)
{
// Check control itself.
if (IsControlUsingLayout(control, layout))
return true;
// Check children.
var children = control.children;
for (var i = 0; i < children.Count; ++i)
if (IsControlOrChildUsingLayoutRecursive(children[i], layout))
return true;
return false;
}
private bool IsControlUsingLayout(InputControl control, InternedString layout)
{
// Check direct match.
if (control.layout == layout)
return true;
// Check base layout chain.
var baseLayout = control.m_Layout;
while (m_Layouts.baseLayoutTable.TryGetValue(baseLayout, out baseLayout))
if (baseLayout == layout)
return true;
return false;
}
public void RegisterControlLayoutMatcher(string layoutName, InputDeviceMatcher matcher)
{
if (string.IsNullOrEmpty(layoutName))
throw new ArgumentNullException(nameof(layoutName));
if (matcher.empty)
throw new ArgumentException("Matcher cannot be empty", nameof(matcher));
// Add to table.
var internedLayoutName = new InternedString(layoutName);
m_Layouts.AddMatcher(internedLayoutName, matcher);
// Recreate any device that we match better than its current layout.
RecreateDevicesUsingLayoutWithInferiorMatch(matcher);
// See if we can make sense of any device we couldn't make sense of before.
AddAvailableDevicesMatchingDescription(matcher, internedLayoutName);
}
public void RegisterControlLayoutMatcher(Type type, InputDeviceMatcher matcher)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (matcher.empty)
throw new ArgumentException("Matcher cannot be empty", nameof(matcher));
var layoutName = m_Layouts.TryFindLayoutForType(type);
if (layoutName.IsEmpty())
throw new ArgumentException(
$"Type '{type.Name}' has not been registered as a control layout", nameof(type));
RegisterControlLayoutMatcher(layoutName, matcher);
}
private void RecreateDevicesUsingLayoutWithInferiorMatch(InputDeviceMatcher deviceMatcher)
{
if (m_DevicesCount == 0)
return;
using (InputDeviceBuilder.Ref())
{
var deviceCount = m_DevicesCount;
for (var i = 0; i < deviceCount; ++i)
{
var device = m_Devices[i];
var deviceDescription = device.description;
if (deviceDescription.empty || !(deviceMatcher.MatchPercentage(deviceDescription) > 0))
continue;
var layoutName = TryFindMatchingControlLayout(ref deviceDescription, device.deviceId);
if (layoutName != device.m_Layout)
{
device.m_Description = deviceDescription;
RecreateDevice(device, layoutName);
// We're removing devices in the middle of the array and appending
// them at the end. Adjust our index and device count to make sure
// we're not iterating all the way into already processed devices.
--i;
--deviceCount;
}
}
}
}
private void RecreateDevice(InputDevice oldDevice, InternedString newLayout)
{
// Remove.
RemoveDevice(oldDevice, keepOnListOfAvailableDevices: true);
// Re-setup device.
var newDevice = InputDevice.Build<InputDevice>(newLayout, oldDevice.m_Variants,
deviceDescription: oldDevice.m_Description);
// Preserve device properties that should not be changed by the re-creation
// of a device.
newDevice.m_DeviceId = oldDevice.m_DeviceId;
newDevice.m_Description = oldDevice.m_Description;
if (oldDevice.native)
newDevice.m_DeviceFlags |= InputDevice.DeviceFlags.Native;
if (oldDevice.remote)
newDevice.m_DeviceFlags |= InputDevice.DeviceFlags.Remote;
if (!oldDevice.enabled)
{
newDevice.m_DeviceFlags |= InputDevice.DeviceFlags.DisabledStateHasBeenQueriedFromRuntime;
newDevice.m_DeviceFlags |= InputDevice.DeviceFlags.DisabledInFrontend;
}
// Re-add.
AddDevice(newDevice);
}
private void AddAvailableDevicesMatchingDescription(InputDeviceMatcher matcher, InternedString layout)
{
#if UNITY_EDITOR
// If we still have some devices saved from the last domain reload, see
// if they are matched by the given matcher. If so, turn them into devices.
for (var i = 0; i < m_SavedDeviceStates.LengthSafe(); ++i)
{
ref var deviceState = ref m_SavedDeviceStates[i];
if (matcher.MatchPercentage(deviceState.description) > 0)
{
RestoreDeviceFromSavedState(ref deviceState, layout);
ArrayHelpers.EraseAt(ref m_SavedDeviceStates, i);
--i;
}
}
#endif
// See if the new description to layout mapping allows us to make
// sense of a device we couldn't make sense of so far.
for (var i = 0; i < m_AvailableDeviceCount; ++i)
{
// Ignore if it's a device that has been explicitly removed.
if (m_AvailableDevices[i].isRemoved)
continue;
var deviceId = m_AvailableDevices[i].deviceId;
if (TryGetDeviceById(deviceId) != null)
continue;
if (matcher.MatchPercentage(m_AvailableDevices[i].description) > 0f)
{
// Try to create InputDevice instance.
try
{
AddDevice(layout, deviceId, deviceDescription: m_AvailableDevices[i].description,
deviceFlags: m_AvailableDevices[i].isNative ? InputDevice.DeviceFlags.Native : 0);
}
catch (Exception exception)
{
Debug.LogError(
$"Layout '{layout}' matches existing device '{m_AvailableDevices[i].description}' but failed to instantiate: {exception}");
Debug.LogException(exception);
continue;
}
// Re-enable device.
var command = EnableDeviceCommand.Create();
m_Runtime.DeviceCommand(deviceId, ref command);
}
}
}
public void RemoveControlLayout(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(name));
var internedName = new InternedString(name);
// Remove all devices using the layout.
for (var i = 0; i < m_DevicesCount;)
{
var device = m_Devices[i];
if (IsControlOrChildUsingLayoutRecursive(device, internedName))
{
RemoveDevice(device, keepOnListOfAvailableDevices: true);
}
else
{
++i;
}
}
// Remove layout record.
m_Layouts.layoutTypes.Remove(internedName);
m_Layouts.layoutStrings.Remove(internedName);
m_Layouts.layoutBuilders.Remove(internedName);
m_Layouts.baseLayoutTable.Remove(internedName);
++m_LayoutRegistrationVersion;
////TODO: check all layout inheritance chain for whether they are based on the layout and if so
//// remove those layouts, too
// Let listeners know.
DelegateHelpers.InvokeCallbacksSafe(ref m_LayoutChangeListeners, name, InputControlLayoutChange.Removed, k_InputOnLayoutChangeMarker, "InputSystem.onLayoutChange");
}
public InputControlLayout TryLoadControlLayout(Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (!typeof(InputControl).IsAssignableFrom(type))
throw new ArgumentException($"Type '{type.Name}' is not an InputControl", nameof(type));
// Find the layout name that the given type was registered with.
var layoutName = m_Layouts.TryFindLayoutForType(type);
if (layoutName.IsEmpty())
throw new ArgumentException(
$"Type '{type.Name}' has not been registered as a control layout", nameof(type));
return m_Layouts.TryLoadLayout(layoutName);
}
public InputControlLayout TryLoadControlLayout(InternedString name)
{
return m_Layouts.TryLoadLayout(name);
}
////FIXME: allowing the description to be modified as part of this is surprising; find a better way
public InternedString TryFindMatchingControlLayout(ref InputDeviceDescription deviceDescription, int deviceId = InputDevice.InvalidDeviceId)
{
InternedString layoutName = new InternedString(string.Empty);
try
{
k_InputTryFindMatchingControllerMarker.Begin();
////TODO: this will want to take overrides into account
// See if we can match by description.
layoutName = m_Layouts.TryFindMatchingLayout(deviceDescription);
if (layoutName.IsEmpty())
{
// No, so try to match by device class. If we have a "Gamepad" layout,
// for example, a device that classifies itself as a "Gamepad" will match
// that layout.
//
// NOTE: Have to make sure here that we get a device layout and not a
// control layout.
if (!string.IsNullOrEmpty(deviceDescription.deviceClass))
{
var deviceClassLowerCase = new InternedString(deviceDescription.deviceClass);
var type = m_Layouts.GetControlTypeForLayout(deviceClassLowerCase);
if (type != null && typeof(InputDevice).IsAssignableFrom(type))
layoutName = new InternedString(deviceDescription.deviceClass);
}
}
////REVIEW: listeners registering new layouts from in here may potentially lead to the creation of devices; should we disallow that?
////REVIEW: if a callback picks a layout, should we re-run through the list of callbacks? or should we just remove haveOverridenLayoutName?
// Give listeners a shot to select/create a layout.
if (m_DeviceFindLayoutCallbacks.length > 0)
{
// First time we get here, put our delegate for executing device commands
// in place. We wrap the call to IInputRuntime.DeviceCommand so that we don't
// need to expose the runtime to the onFindLayoutForDevice callbacks.
if (m_DeviceFindExecuteCommandDelegate == null)
m_DeviceFindExecuteCommandDelegate =
(ref InputDeviceCommand commandRef) =>
{
if (m_DeviceFindExecuteCommandDeviceId == InputDevice.InvalidDeviceId)
return InputDeviceCommand.GenericFailure;
return m_Runtime.DeviceCommand(m_DeviceFindExecuteCommandDeviceId, ref commandRef);
};
m_DeviceFindExecuteCommandDeviceId = deviceId;
var haveOverriddenLayoutName = false;
m_DeviceFindLayoutCallbacks.LockForChanges();
for (var i = 0; i < m_DeviceFindLayoutCallbacks.length; ++i)
{
try
{
var newLayout = m_DeviceFindLayoutCallbacks[i](ref deviceDescription, layoutName, m_DeviceFindExecuteCommandDelegate);
if (!string.IsNullOrEmpty(newLayout) && !haveOverriddenLayoutName)
{
layoutName = new InternedString(newLayout);
haveOverriddenLayoutName = true;
}
}
catch (Exception exception)
{
Debug.LogError($"{exception.GetType().Name} while executing 'InputSystem.onFindLayoutForDevice' callbacks");
Debug.LogException(exception);
}
}
m_DeviceFindLayoutCallbacks.UnlockForChanges();
}
}
finally
{
k_InputTryFindMatchingControllerMarker.End();
}
return layoutName;
}
private InternedString FindOrRegisterDeviceLayoutForType(Type type)
{
var layoutName = m_Layouts.TryFindLayoutForType(type);
if (layoutName.IsEmpty())
{
// Automatically register the given type as a layout.
if (layoutName.IsEmpty())
{
layoutName = new InternedString(type.Name);
RegisterControlLayout(type.Name, type);
}
}
return layoutName;
}
/// <summary>
/// Return true if the given device layout is supported by the game according to <see cref="InputSettings.supportedDevices"/>.