forked from MixedRealityToolkit/MixedRealityToolkit-Unity
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInputSimulator.cs
More file actions
768 lines (662 loc) · 31.4 KB
/
Copy pathInputSimulator.cs
File metadata and controls
768 lines (662 loc) · 31.4 KB
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
// Copyright (c) Mixed Reality Toolkit Contributors
// Licensed under the BSD 3-Clause
using Unity.Profiling;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.LowLevel;
using UnityEngine.XR;
using UnityEngine.XR.Interaction.Toolkit;
using UnityEngine.XR.Interaction.Toolkit.Inputs;
namespace MixedReality.Toolkit.Input.Simulation
{
/// <summary>
/// Input device and HMD navigation simulator.
/// </summary>
[AddComponentMenu("MRTK/Input/Input Simulator")]
[DefaultExecutionOrder(XRInteractionUpdateOrder.k_DeviceSimulator)]
public class InputSimulator : MonoBehaviour
{
#region MonoBehaviour
/// <summary>
/// A Unity event function that is called when an enabled script instance is being loaded.
/// </summary>
private void Awake()
{
ApplyControlSet(ControlSet);
}
private static readonly ProfilerMarker UpdatePerfMarker =
new ProfilerMarker("[MRTK] InputSimulator.Update");
private bool isSimulating = true;
/// <summary>
/// A Unity event function that is called every frame, if this object is enabled.
/// </summary>
private void Update()
{
using (UpdatePerfMarker.Auto())
{
bool shouldSimulate = !XRDisplaySubsystemHelpers.AreAnyActive();
if (isSimulating != shouldSimulate)
{
isSimulating = shouldSimulate;
if (!isSimulating)
{
DisableSimulatedHMD();
DisableSimulatedEyeGaze();
DisableSimulatedController(Handedness.Left);
DisableSimulatedController(Handedness.Right);
}
}
if (!isSimulating)
{
return;
}
// Camera
if (cameraSettings.SimulationEnabled)
{
EnableSimulatedHMD();
UpdateSimulatedHMD();
}
else
{
DisableSimulatedHMD();
}
// Eyes
if (eyeGazeSettings.SimulationEnabled)
{
EnableSimulatedEyeGaze();
UpdateSimulatedEyeGaze();
}
else
{
DisableSimulatedEyeGaze();
}
// Controllers/Hands
if (leftControllerSettings.SimulationMode != ControllerSimulationMode.Disabled)
{
UpdateSimulatedController(Handedness.Left);
}
else
{
DisableSimulatedController(Handedness.Left);
}
if (rightControllerSettings.SimulationMode != ControllerSimulationMode.Disabled)
{
UpdateSimulatedController(Handedness.Right);
}
else
{
DisableSimulatedController(Handedness.Right);
}
}
}
/// <summary>
/// A Unity event function that is called when the script component has been disabled.
/// </summary>
private void OnDisable()
{
DisableSimulatedHMD();
DisableSimulatedEyeGaze();
DisableSimulatedController(Handedness.Left);
DisableSimulatedController(Handedness.Right);
}
#endregion MonoBehaviour
#region Camera
private SimulatedHMD simulatedHMD = null;
[SerializeField]
[Tooltip("Input simulation control compatibility set")]
private SimulatorControlScheme controlSet = null;
/// <summary>
/// Input simulation control compatibility set.
/// </summary>
public SimulatorControlScheme ControlSet
{
get => controlSet;
set => controlSet = value;
}
[SerializeField]
private CameraSimulationSettings cameraSettings;
/// <summary>
/// The settings used to configure and control the simulated camera.
/// </summary>
public CameraSimulationSettings CameraSettings
{
get => cameraSettings;
set => cameraSettings = value;
}
/// <summary>
/// Enables simulated camera control.
/// </summary>
/// <remarks>
/// This method creates the camera simulation object(s) as needed. If called while
/// already enabled, this method does nothing.
/// </remarks>
private void EnableSimulatedHMD()
{
simulatedHMD ??= new SimulatedHMD();
}
/// <summary>
/// Disables simulated camera control.
/// </summary>
/// <remarks>
/// This method cleans up the camera simulation object(s) as needed. If called while
/// already enabled, this method does nothing.
/// </remarks>
private void DisableSimulatedHMD()
{
if (simulatedHMD != null)
{
simulatedHMD.Dispose();
simulatedHMD = null;
}
}
private static readonly ProfilerMarker UpdateSimulatedHMDPerfMarker =
new ProfilerMarker("[MRTK] InputSimulator.UpdateSimulatedHMD");
/// <summary>
/// Updates the camera simulation.
/// </summary>
private void UpdateSimulatedHMD()
{
if (simulatedHMD == null) { return; }
using (UpdateSimulatedHMDPerfMarker.Auto())
{
// Get the position change
Vector3 positionDelta = new Vector3(
CameraSettings.MoveHorizontal.action.ReadValue<float>(),
CameraSettings.MoveVertical.action.ReadValue<float>(),
CameraSettings.MoveDepth.action.ReadValue<float>());
// Get the rotation change
Vector3 rotationDelta = new Vector3(
// Unity inverts the camera pitch by default, mirroring how the neck works (move forward to look down)
CameraSettings.Pitch.action.ReadValue<float>() * (!CameraSettings.InvertPitch ? -1 : 1),
CameraSettings.Yaw.action.ReadValue<float>(),
CameraSettings.Roll.action.ReadValue<float>());
// Update the simulated camera
simulatedHMD.Update(
positionDelta * 0.1f,
rotationDelta,
CameraSettings.IsMovementSmoothed,
CameraSettings.MoveSpeed,
CameraSettings.RotationSensitivity,
CameraSettings.IsFrameRateIndependent);
}
}
#endregion Camera
#region Eyes
private SimulatedEyeGaze simulatedEyeGaze = null;
[SerializeField]
private EyeGazeSimulationSettings eyeGazeSettings;
/// <summary>
/// The settings used to configure and control the simulated eye gaze.
/// </summary>
public EyeGazeSimulationSettings EyeGazeSettings
{
get => eyeGazeSettings;
set => eyeGazeSettings = value;
}
/// <summary>
/// Enables simulated eye gaze.
/// </summary>
/// <remarks>
/// This method creates the eye gaze simulation object(s) as needed. If called while
/// already enabled, this method does nothing.
/// </remarks>
private void EnableSimulatedEyeGaze()
{
simulatedEyeGaze ??= new SimulatedEyeGaze();
}
/// <summary>
/// Disables simulated eye gaze.
/// </summary>
/// <remarks>
/// This method cleans up the eye gaze simulation object(s) as needed. If called while
/// already disabled, this method does nothing.
/// </remarks>
private void DisableSimulatedEyeGaze()
{
if (simulatedEyeGaze != null)
{
simulatedEyeGaze.Dispose();
simulatedEyeGaze = null;
}
}
private static readonly ProfilerMarker UpdateSimulatedEyesPerfMarker =
new ProfilerMarker("[MRTK] InputSimulator.UpdateSimulatedEyes");
/// <summary>
/// Updates the eye gaze simulation.
/// </summary>
private void UpdateSimulatedEyeGaze()
{
if (simulatedEyeGaze == null) { return; }
using (UpdateSimulatedEyesPerfMarker.Auto())
{
Vector3 lookDelta = new Vector3(
-eyeGazeSettings.LookVertical.action.ReadValue<float>(),
eyeGazeSettings.LookHorizontal.action.ReadValue<float>(),
0f);
simulatedEyeGaze.Update(
true,
lookDelta,
eyeGazeSettings.EyeOriginOffset);
}
}
#endregion Eyes
#region Controllers
private SimulatedController simulatedLeftController = null;
private float leftTriggerSmoothVelocity;
private SimulatedController simulatedRightController = null;
private float rightTriggerSmoothVelocity;
private ControllerControls leftControllerControls = new ControllerControls();
private ControllerControls rightControllerControls = new ControllerControls();
[SerializeField]
private ControllerSimulationSettings leftControllerSettings;
/// <summary>
/// The settings used to configure and control the simulated left hand/controller.
/// </summary>
public ControllerSimulationSettings LeftControllerSettings
{
get => leftControllerSettings;
set => leftControllerSettings = value;
}
[SerializeField]
private ControllerSimulationSettings rightControllerSettings;
/// <summary>
/// The settings used to configure and control the simulated right hand/controller.
/// </summary>
public ControllerSimulationSettings RightControllerSettings
{
get => rightControllerSettings;
set => rightControllerSettings = value;
}
// TODO: Drive from inspector/simulator options.
private float triggerSmoothTime = 0.1f;
// TODO: Drive from inspector/simulator options.
private float triggerSmoothDeadzone = 0.005f;
/// <summary>
/// Enables the simulated controller.
/// </summary>
/// <param name="handedness">
/// The <see cref="Handedness"/> of the controller to be enabled.
/// </param>
/// <param name="ctrlSettings">
/// The controller simulation settings to use the simulation.
/// </param>
/// <param name="startPosition">
/// The initial position of the simulated controller.
/// </param>
/// <remarks>
/// This method creates the controller simulation object(s) as needed. If called while
/// already enabled, this method does nothing.
/// </remarks>
/// <returns>
/// Current, or created, <see cref="SimulatedController"/> instance or null.
/// </returns>
private SimulatedController EnableSimulatedController(
Handedness handedness,
ControllerSimulationSettings ctrlSettings,
Vector3 startPosition)
{
if (!IsSupportedHandedness(handedness))
{
Debug.LogError($"Unable to enable simulated controller. Unsupported handedness ({handedness}).");
return null;
}
ref SimulatedController simCtrl = ref GetControllerReference(handedness);
if (simCtrl != null) { return simCtrl; }
simCtrl = new SimulatedController(handedness, ctrlSettings, startPosition);
ControllerControls controls = GetControllerControls(handedness);
controls.Reset();
return simCtrl;
}
/// <summary>
/// Disables the simulated controller.
/// </summary>
/// <param name="handedness">
/// The <see cref="Handedness"/> of the controller to be disabled.
/// </param>
/// <remarks>
/// This method cleans up controller simulation object(s) as needed. If called while
/// already enabled, this method does nothing.
/// </remarks>
private void DisableSimulatedController(Handedness handedness)
{
if (!IsSupportedHandedness(handedness))
{
Debug.Log($"Unable to disable simulated controller. Unsupported handedness ({handedness}).");
return;
}
ref SimulatedController simCtrl = ref GetControllerReference(handedness);
if (simCtrl == null) { return; }
simCtrl.Dispose();
simCtrl = null;
}
private static readonly ProfilerMarker UpdateSimulatedControllerPerfMarker =
new ProfilerMarker("[MRTK] InputSimulator.UpdateSimulatedController");
private static readonly Quaternion NoRotation = Quaternion.Euler(0f, 0f, 0f);
/// <summary>
/// Updates the controller simulation.
/// </summary>
/// <param name="handedness">
/// The <see cref="Handedness"/> of the controller to be updated.
/// </param>
private void UpdateSimulatedController(Handedness handedness)
{
using (UpdateSimulatedControllerPerfMarker.Auto())
{
if (!IsSupportedHandedness(handedness))
{
Debug.Log($"Unable to update the simulated controller. Unsupported handedness ({handedness}).");
return;
}
ControllerSimulationSettings ctrlSettings = (handedness == Handedness.Left) ?
leftControllerSettings : rightControllerSettings;
if (ctrlSettings == null) { return; }
// Has the user toggled latched tracking?
if (ctrlSettings.Toggle.action.WasPerformedThisFrame())
{
ctrlSettings.ToggleState = !ctrlSettings.ToggleState;
}
// Is momentary tracking enabled?
bool isMomentarilyTracked = ctrlSettings.Track.action.IsPressed();
ref SimulatedController simCtrl = ref GetControllerReference(handedness);
if (ctrlSettings.ToggleState || isMomentarilyTracked)
{
if (simCtrl == null)
{
// Get the start position for the controller.
Vector3 startPosition = ctrlSettings.DefaultPosition;
if (isMomentarilyTracked)
{
Vector3 screenPos = new Vector3(
Mouse.current.position.ReadValue().x,
Mouse.current.position.ReadValue().y,
ctrlSettings.DefaultPosition.z);
startPosition = ScreenToCameraRelative(screenPos);
}
// Create the simulated controller.
simCtrl = EnableSimulatedController(
handedness,
ctrlSettings,
startPosition);
}
}
else
{
DisableSimulatedController(handedness);
simCtrl = null;
}
if (simCtrl == null) { return; }
ControllerControls controls = GetControllerControls(handedness);
Vector3 positionDelta = Vector3.zero;
Quaternion rotationDelta = NoRotation;
if (isMomentarilyTracked)
{
// Has the user asked to change the neutral pose?
if (ctrlSettings.ToggleSecondaryHandshapes.action.WasPerformedThisFrame())
{
simCtrl.ToggleNeutralPose();
}
// Is our simulated controller controlled by a mouse? If so, we should
// calculate the desired delta from the mouse position on screen.
bool isControlledByMouse = ctrlSettings.MoveHorizontal.action.RaisedByMouse() ||
ctrlSettings.MoveVertical.action.RaisedByMouse();
bool isControllingRotation = ctrlSettings.Pitch.action.IsPressed() ||
ctrlSettings.Yaw.action.IsPressed() ||
ctrlSettings.Roll.action.IsPressed();
// Update the rotation mode if the user wants to face the camera
if (ctrlSettings.FaceTheCamera.action.WasPerformedThisFrame())
{
ctrlSettings.RotationMode = (ctrlSettings.RotationMode == ControllerRotationMode.FaceCamera) ?
ControllerRotationMode.CameraAligned : ControllerRotationMode.FaceCamera;
}
else if (isControllingRotation)
{
// Ignore position delta if the user is trying to manually rotate the hand
rotationDelta = Quaternion.Euler(
// Unity appears to invert the controller pitch by default (move forward to look down)
ctrlSettings.Pitch.action.ReadValue<float>() * (!ctrlSettings.InvertPitch ? -1 : 1),
ctrlSettings.Yaw.action.ReadValue<float>(),
ctrlSettings.Roll.action.ReadValue<float>());
if (rotationDelta != NoRotation) { ctrlSettings.RotationMode = ControllerRotationMode.UserControl; }
}
else
{
if (isControlledByMouse && !ctrlSettings.ToggleState) // If tracking is latched, we do not want to 1:1 track the mouse location.
{
/* TODO: this needs work, also depth moves the hands towards the vanishing point
Vector3 screenDepth = CameraRelativeToScreen(new Vector3(
simCtrl.RelativePosition.z,
0f, ctrlSettings.DefaultPosition.z));
*/
Vector3 mouseScreenPos = new Vector3(
Mouse.current.position.ReadValue().x,
Mouse.current.position.ReadValue().y,
ctrlSettings.DefaultPosition.z);
// TODO: related to the above - screenDepth.x + ctrlSettings.MoveDepth.action.ReadValue<float>());
Vector3 inputPosition = ScreenToCameraRelative(mouseScreenPos);
positionDelta = inputPosition - simCtrl.CameraRelativePose.position;
positionDelta.z = ctrlSettings.MoveDepth.action.ReadValue<float>();
}
else
{
positionDelta = new Vector3(
ctrlSettings.MoveHorizontal.action.ReadValue<float>(),
ctrlSettings.MoveVertical.action.ReadValue<float>(),
ctrlSettings.MoveDepth.action.ReadValue<float>());
}
}
ref float triggerSmoothVelocity = ref (handedness == Handedness.Left ? ref leftTriggerSmoothVelocity : ref rightTriggerSmoothVelocity);
// TODO: Currently triggerAxis is driven only from ctrlSettings.TriggerButton.action.
// We will eventually drive this from the ctrlSettings.TriggerAxis.action as well.
// Needs work to be able to intuitively combine trigger axis from sim input with click.
float targetValue = ctrlSettings.TriggerButton.action.IsPressed() ? 1 : 0;
controls.TriggerAxis = Mathf.SmoothDamp(controls.TriggerAxis,
targetValue,
ref triggerSmoothVelocity,
triggerSmoothTime);
if (Mathf.Abs(controls.TriggerAxis - targetValue) < triggerSmoothDeadzone)
{
controls.TriggerAxis = targetValue;
}
#if LATER
// TODO: mappings need to be sorted out for these
// Axes available to hands and controllers
float axisDeltaReading = ctrlSettings.TriggerAxis.action.ReadValue<float>();
if ((axisDeltaReading != 0) && (controls.TriggerAxis != axisDeltaReading))
{
controls.TriggerAxis += axisDeltaReading;
}
axisDeltaReading = ctrlSettings.GripAxis.action.ReadValue<float>();
if ((axisDeltaReading != 0) && (controls.GripAxis != axisDeltaReading))
{
controls.GripAxis += axisDeltaReading;
}
#endif // LATER
// Buttons available to hands and controllers
controls.TriggerButton = controls.TriggerAxis >= InputSystem.settings.defaultButtonPressPoint;
controls.GripButton = ctrlSettings.GripButton.action.IsPressed();
if (ctrlSettings.SimulationMode == ControllerSimulationMode.MotionController)
{
// Axes available to controllers
// TODO: https://github.com/MixedRealityToolkit/MixedRealityToolkit-Unity/issues/734
// controls.Primary2DAxis = ctrlSettings.Primary2DAxis.action.ReadValue(float)();
// controls.Secondary2DAxis = ctrlSettings.Secondary2DAxis.action.ReadValue(float)();
// Buttons available to controllers
// TODO: https://github.com/MixedRealityToolkit/MixedRealityToolkit-Unity/issues/734
// controls.MenuButton = ctrlSettings.MenuButton.action.ReadValue(float)() > 0f;
// controls.PrimaryButton = ctrlSettings.PrimaryButton.action.ReadValue(float)() > 0f;
// controls.SecondaryButton = ctrlSettings.SecondaryButton.action.ReadValue(float)() > 0f;
// controls.PrimaryTouch = ctrlSettings.PrimaryTouch.action.ReadValue(float)() > 0f;
// controls.SecondaryTouch = ctrlSettings.SecondaryTouch.action.ReadValue(float)() > 0f;
// controls.Primary2DAxisClick = ctrlSettings.Primary2DAxisClick.action.ReadValue(float)() > 0f;
// controls.Secondary2DAxisClick = ctrlSettings.Secondary2DAxisClick.action.ReadValue(float)() > 0f;
// controls.Primary2DAxisTouch = ctrlSettings.Primary2DAxisTouch.action.ReadValue(float)() > 0f;
// controls.Secondary2DAxisTouch = ctrlSettings.Secondary2DAxisTouch.action.ReadValue(float)() > 0f;
}
}
controls.IsTracked = ctrlSettings.ToggleState || isMomentarilyTracked;
controls.TrackingState = controls.IsTracked ?
(InputTrackingState.Position | InputTrackingState.Rotation) : InputTrackingState.None;
bool shouldUseRayVector = ctrlSettings.SimulationMode == ControllerSimulationMode.ArticulatedHand;
// determine which offset we are using
Vector3 anchorPosition = simCtrl.WorldPosition;
switch (ctrlSettings.AnchorPoint)
{
case ControllerAnchorPoint.Device:
anchorPosition = simCtrl.WorldPosition;
break;
case ControllerAnchorPoint.IndexFinger:
anchorPosition = simCtrl.PokePosition;
break;
case ControllerAnchorPoint.Grab:
anchorPosition = simCtrl.GrabPosition;
break;
}
simCtrl.UpdateRelative(
positionDelta,
rotationDelta,
controls,
ctrlSettings.RotationMode,
shouldUseRayVector,
anchorPosition,
ctrlSettings.IsMovementSmoothed,
ctrlSettings.DepthSensitivity,
ctrlSettings.JitterStrength);
}
}
/// <summary>
/// Converts a camera relative location into screen (ex: within the Unity Editor window) space.
/// </summary>
/// <param name="cameraRelativePos">The location relative to the camera to convert.</param>
/// <returns>
/// Location in screen space.
/// </returns>
private Vector3 CameraRelativeToScreen(Vector3 cameraRelativePos)
{
// First, convert from the camera space to world space.
Vector3 worldPos = Camera.main.transform.TransformPoint(cameraRelativePos);
// Then convert from world to screen space.
return Camera.main.WorldToScreenPoint(worldPos);
}
/// <summary>
/// Converts a screen location (ex: within the Unity Editor window) into camera relative space.
/// </summary>
/// <param name="screenPos">The location on screen to convert.</param>
/// <returns>
/// Location relative to the game window's camera space.
/// </returns>
private Vector3 ScreenToCameraRelative(Vector3 screenPos)
{
// First, convert from the screen space to world space.
Vector3 worldPos = Camera.main.ScreenToWorldPoint(screenPos);
// Then convert from world to camera relative space.
return Camera.main.transform.InverseTransformPoint(worldPos);
}
/// <summary>
/// Determines if the specified <see cref="Handedness"/> is supported by the input simulator.
/// </summary>
/// <param name="handedness"><see cref="Handedness"/> value (ex: Left).</param>
/// <returns>
/// <see langword="true"/> if the specified <see cref="Handedness"/> is supported, or <see langword="false"/>.
/// </returns>
private bool IsSupportedHandedness(Handedness handedness)
{
return !((handedness != Handedness.Left) && (handedness != Handedness.Right));
}
private static readonly string UnsupportedHandednessLog = $"Unsupported Handedness. Must be {Handedness.Left} or {Handedness.Right}";
/// <summary>
/// Gets a reference to the <see cref="SimulatedController"/> indicated by the
/// specified <see cref="Handedness"/>.
/// </summary>
/// <param name="handedness"><see cref="Handedness"/> value (ex: Left).</param>
/// <returns>
/// The <see cref="SimulatedController"/> associated with the specified <see cref="Handedness"/>.
/// </returns>
private ref SimulatedController GetControllerReference(Handedness handedness)
{
Debug.Assert(
IsSupportedHandedness(handedness),
UnsupportedHandednessLog);
return ref (handedness == Handedness.Left ? ref simulatedLeftController : ref simulatedRightController);
}
/// <summary>
/// Gets a reference to the <see cref="ControllerControls"/> indicated by the
/// specified <see cref="Handedness"/>.
/// </summary>
/// <param name="handedness"><see cref="Handedness"/> value (ex: Left).</param>
/// <returns>
/// The <see cref="ControllerControls"/> associated with the specified <see cref="Handedness"/>.
/// </returns>
private ControllerControls GetControllerControls(Handedness handedness)
{
Debug.Assert(
IsSupportedHandedness(handedness),
UnsupportedHandednessLog);
return handedness == Handedness.Left ? leftControllerControls : rightControllerControls;
}
#endregion Controllers
#region Helpers
private InputActionManager actionManager = null;
/// <summary>
/// Applies the users selected control compatibility set.
/// </summary>
/// <param name="set">the <see cref="SimulatorControlScheme"/> to be applied.</param>
private void ApplyControlSet(SimulatorControlScheme set)
{
if (actionManager == null)
{
if (!TryGetComponent(out actionManager))
{
Debug.LogError("[InputSimulator] No InputActionManager found - unable to apply control set selection.");
return;
}
}
int assetCount = actionManager.actionAssets.Count;
if (assetCount == 0)
{
Debug.LogError("[InputSimulator] InputActionManager has no registered InputActionAssets - unable to apply control set selection.");
return;
}
for (int i = 0; i < assetCount; i++)
{
actionManager.actionAssets[i].bindingMask = new InputBinding() { groups = GetControlSetName(set) };
}
}
/// <summary>
/// Gets the display name for the simulator control set.
/// </summary>
/// <param name="set">the <see cref="SimulatorControlScheme"/> for which the name is being requested.</param>
/// <returns>The <see cref="SimulatorControlScheme"/>'s display name.</returns>
private string GetControlSetName(SimulatorControlScheme set)
{
return set.name;
}
// This is a utility method called by XRSimulatedHMD and XRSimulatedController
// since both devices share the same command handling. This intercepts sync commands
// and returns GenericSuccess. Otherwise, simulated devices will fail to sync and
// cause issues like wonky state after tabbing out/tabbing in.
internal static unsafe bool TryExecuteCommand(InputDeviceCommand* commandPtr, out long result)
{
// This replicates the logic in XRToISXDevice::IOCTL (XRInputToISX.cpp).
var type = commandPtr->type;
if (type == RequestSyncCommand.Type)
{
// The state is maintained by XRDeviceSimulator, so no need for any change
// when focus is regained. Returning success instructs Input System to not
// reset the device.
result = InputDeviceCommand.GenericSuccess;
return true;
}
if (type == QueryCanRunInBackground.Type)
{
// This ensures all simulated devices always report canRunInBackground = true,
// regardless of whether they were explicitly marked as such.
((QueryCanRunInBackground*)commandPtr)->canRunInBackground = true;
result = InputDeviceCommand.GenericSuccess;
return true;
}
result = default;
return false;
}
#endregion Helpers
}
}