BlueGit

blue-star ggj-2020

Files

ggj-2020 / Assets / Oculus / VR / Scripts / Util / OVRInputModule.cs

OVRInputModule.cs

Project Import
timfa Tim Falken · pushed by timfa · 6 years ago
b77834a1 History
OVRInputModule.cs 36.5 KiB Download Raw
1/************************************************************************************
2Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
3
4Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use
5the Utilities SDK except in compliance with the License, which is provided at the time of installation
6or download, or which otherwise accompanies this software in either electronic or hard copy form.
7
8You may obtain a copy of the License at
9https://developer.oculus.com/licenses/utilities-1.31
10
11Unless required by applicable law or agreed to in writing, the Utilities SDK distributed
12under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
13ANY KIND, either express or implied. See the License for the specific language governing
14permissions and limitations under the License.
15************************************************************************************/
16
17using System;
18using System.Collections.Generic;
19
20namespace UnityEngine.EventSystems
21{
22 /// <summary>
23 /// VR extension of PointerInputModule which supports gaze and controller pointing.
24 /// </summary>
25 public class OVRInputModule : PointerInputModule
26 {
27 [Tooltip("Object which points with Z axis. E.g. CentreEyeAnchor from OVRCameraRig")]
28 public Transform rayTransform;
29
30 public OVRCursor m_Cursor;
31
32 [Tooltip("Gamepad button to act as gaze click")]
33 public OVRInput.Button joyPadClickButton = OVRInput.Button.One;
34
35 [Tooltip("Keyboard button to act as gaze click")]
36 public KeyCode gazeClickKey = KeyCode.Space;
37
38 [Header("Physics")]
39 [Tooltip("Perform an sphere cast to determine correct depth for gaze pointer")]
40 public bool performSphereCastForGazepointer;
41
42 [Header("Gamepad Stick Scroll")]
43 [Tooltip("Enable scrolling with the right stick on a gamepad")]
44 public bool useRightStickScroll = true;
45
46 [Tooltip("Deadzone for right stick to prevent accidental scrolling")]
47 public float rightStickDeadZone = 0.15f;
48
49 [Header("Touchpad Swipe Scroll")]
50 [Tooltip("Enable scrolling by swiping the GearVR touchpad")]
51 public bool useSwipeScroll = true;
52 [Tooltip("Minimum trackpad movement in pixels to start swiping")]
53 public float swipeDragThreshold = 2;
54 [Tooltip("Distance scrolled when swipe scroll occurs")]
55 public float swipeDragScale = 1f;
56 /* It's debatable which way left and right are on the Gear VR touchpad since it's facing away from you
57 * the following bool allows this to be swapped*/
58 [Tooltip("Invert X axis on touchpad")]
59 public bool InvertSwipeXAxis = false;
60
61
62 // The raycaster that gets to do pointer interaction (e.g. with a mouse), gaze interaction always works
63 [NonSerialized]
64 public OVRRaycaster activeGraphicRaycaster;
65 [Header("Dragging")]
66 [Tooltip("Minimum pointer movement in degrees to start dragging")]
67 public float angleDragThreshold = 1;
68
69 [SerializeField]
70 private float m_SpherecastRadius = 1.0f;
71
72
73
74
75
76 // The following region contains code exactly the same as the implementation
77 // of StandaloneInputModule. It is copied here rather than inheriting from StandaloneInputModule
78 // because most of StandaloneInputModule is private so it isn't possible to easily derive from.
79 // Future changes from Unity to StandaloneInputModule will make it possible for this class to
80 // derive from StandaloneInputModule instead of PointerInput module.
81 //
82 // The following functions are not present in the following region since they have modified
83 // versions in the next region:
84 // Process
85 // ProcessMouseEvent
86 // UseMouse
87 #region StandaloneInputModule code
88 private float m_NextAction;
89
90 private Vector2 m_LastMousePosition;
91 private Vector2 m_MousePosition;
92
93 protected OVRInputModule()
94 {}
95
96#if UNITY_EDITOR
97 protected override void Reset()
98 {
99 allowActivationOnMobileDevice = true;
100 }
101#endif
102
103 [Obsolete("Mode is no longer needed on input module as it handles both mouse and keyboard simultaneously.", false)]
104 public enum InputMode
105 {
106 Mouse,
107 Buttons
108 }
109
110 [Obsolete("Mode is no longer needed on input module as it handles both mouse and keyboard simultaneously.", false)]
111 public InputMode inputMode
112 {
113 get { return InputMode.Mouse; }
114 }
115 [Header("Standalone Input Module")]
116 [SerializeField]
117 private string m_HorizontalAxis = "Horizontal";
118
119 /// <summary>
120 /// Name of the vertical axis for movement (if axis events are used).
121 /// </summary>
122 [SerializeField]
123 private string m_VerticalAxis = "Vertical";
124
125 /// <summary>
126 /// Name of the submit button.
127 /// </summary>
128 [SerializeField]
129 private string m_SubmitButton = "Submit";
130
131 /// <summary>
132 /// Name of the submit button.
133 /// </summary>
134 [SerializeField]
135 private string m_CancelButton = "Cancel";
136
137 [SerializeField]
138 private float m_InputActionsPerSecond = 10;
139
140 [SerializeField]
141 private bool m_AllowActivationOnMobileDevice;
142
143 public bool allowActivationOnMobileDevice
144 {
145 get { return m_AllowActivationOnMobileDevice; }
146 set { m_AllowActivationOnMobileDevice = value; }
147 }
148
149 public float inputActionsPerSecond
150 {
151 get { return m_InputActionsPerSecond; }
152 set { m_InputActionsPerSecond = value; }
153 }
154
155 /// <summary>
156 /// Name of the horizontal axis for movement (if axis events are used).
157 /// </summary>
158 public string horizontalAxis
159 {
160 get { return m_HorizontalAxis; }
161 set { m_HorizontalAxis = value; }
162 }
163
164 /// <summary>
165 /// Name of the vertical axis for movement (if axis events are used).
166 /// </summary>
167 public string verticalAxis
168 {
169 get { return m_VerticalAxis; }
170 set { m_VerticalAxis = value; }
171 }
172
173 public string submitButton
174 {
175 get { return m_SubmitButton; }
176 set { m_SubmitButton = value; }
177 }
178
179 public string cancelButton
180 {
181 get { return m_CancelButton; }
182 set { m_CancelButton = value; }
183 }
184
185 public override void UpdateModule()
186 {
187 m_LastMousePosition = m_MousePosition;
188 m_MousePosition = Input.mousePosition;
189 }
190
191 public override bool IsModuleSupported()
192 {
193 // Check for mouse presence instead of whether touch is supported,
194 // as you can connect mouse to a tablet and in that case we'd want
195 // to use StandaloneInputModule for non-touch input events.
196 return m_AllowActivationOnMobileDevice || Input.mousePresent;
197 }
198
199 public override bool ShouldActivateModule()
200 {
201 if (!base.ShouldActivateModule())
202 return false;
203
204 var shouldActivate = Input.GetButtonDown(m_SubmitButton);
205 shouldActivate |= Input.GetButtonDown(m_CancelButton);
206 shouldActivate |= !Mathf.Approximately(Input.GetAxisRaw(m_HorizontalAxis), 0.0f);
207 shouldActivate |= !Mathf.Approximately(Input.GetAxisRaw(m_VerticalAxis), 0.0f);
208 shouldActivate |= (m_MousePosition - m_LastMousePosition).sqrMagnitude > 0.0f;
209 shouldActivate |= Input.GetMouseButtonDown(0);
210 return shouldActivate;
211 }
212
213 public override void ActivateModule()
214 {
215 base.ActivateModule();
216 m_MousePosition = Input.mousePosition;
217 m_LastMousePosition = Input.mousePosition;
218
219 var toSelect = eventSystem.currentSelectedGameObject;
220 if (toSelect == null)
221 toSelect = eventSystem.firstSelectedGameObject;
222
223 eventSystem.SetSelectedGameObject(toSelect, GetBaseEventData());
224 }
225
226 public override void DeactivateModule()
227 {
228 base.DeactivateModule();
229 ClearSelection();
230 }
231
232
233
234 /// <summary>
235 /// Process submit keys.
236 /// </summary>
237 private bool SendSubmitEventToSelectedObject()
238 {
239 if (eventSystem.currentSelectedGameObject == null)
240 return false;
241
242 var data = GetBaseEventData();
243 if (Input.GetButtonDown(m_SubmitButton))
244 ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.submitHandler);
245
246 if (Input.GetButtonDown(m_CancelButton))
247 ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.cancelHandler);
248 return data.used;
249 }
250
251 private bool AllowMoveEventProcessing(float time)
252 {
253 bool allow = Input.GetButtonDown(m_HorizontalAxis);
254 allow |= Input.GetButtonDown(m_VerticalAxis);
255 allow |= (time > m_NextAction);
256 return allow;
257 }
258
259 private Vector2 GetRawMoveVector()
260 {
261 Vector2 move = Vector2.zero;
262 move.x = Input.GetAxisRaw(m_HorizontalAxis);
263 move.y = Input.GetAxisRaw(m_VerticalAxis);
264
265 if (Input.GetButtonDown(m_HorizontalAxis))
266 {
267 if (move.x < 0)
268 move.x = -1f;
269 if (move.x > 0)
270 move.x = 1f;
271 }
272 if (Input.GetButtonDown(m_VerticalAxis))
273 {
274 if (move.y < 0)
275 move.y = -1f;
276 if (move.y > 0)
277 move.y = 1f;
278 }
279 return move;
280 }
281
282 /// <summary>
283 /// Process keyboard events.
284 /// </summary>
285 private bool SendMoveEventToSelectedObject()
286 {
287 float time = Time.unscaledTime;
288
289 if (!AllowMoveEventProcessing(time))
290 return false;
291
292 Vector2 movement = GetRawMoveVector();
293 // Debug.Log(m_ProcessingEvent.rawType + " axis:" + m_AllowAxisEvents + " value:" + "(" + x + "," + y + ")");
294 var axisEventData = GetAxisEventData(movement.x, movement.y, 0.6f);
295 if (!Mathf.Approximately(axisEventData.moveVector.x, 0f)
296 || !Mathf.Approximately(axisEventData.moveVector.y, 0f))
297 {
298 ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, axisEventData, ExecuteEvents.moveHandler);
299 }
300 m_NextAction = time + 1f / m_InputActionsPerSecond;
301 return axisEventData.used;
302 }
303
304
305
306
307
308 private bool SendUpdateEventToSelectedObject()
309 {
310 if (eventSystem.currentSelectedGameObject == null)
311 return false;
312
313 var data = GetBaseEventData();
314 ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.updateSelectedHandler);
315 return data.used;
316 }
317
318 /// <summary>
319 /// Process the current mouse press.
320 /// </summary>
321 private void ProcessMousePress(MouseButtonEventData data)
322 {
323 var pointerEvent = data.buttonData;
324 var currentOverGo = pointerEvent.pointerCurrentRaycast.gameObject;
325
326 // PointerDown notification
327 if (data.PressedThisFrame())
328 {
329 pointerEvent.eligibleForClick = true;
330 pointerEvent.delta = Vector2.zero;
331 pointerEvent.dragging = false;
332 pointerEvent.useDragThreshold = true;
333 pointerEvent.pressPosition = pointerEvent.position;
334 if (pointerEvent.IsVRPointer())
335 {
336 pointerEvent.SetSwipeStart(Input.mousePosition);
337 }
338 pointerEvent.pointerPressRaycast = pointerEvent.pointerCurrentRaycast;
339
340 DeselectIfSelectionChanged(currentOverGo, pointerEvent);
341
342 // search for the control that will receive the press
343 // if we can't find a press handler set the press
344 // handler to be what would receive a click.
345 var newPressed = ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.pointerDownHandler);
346
347 // didnt find a press handler... search for a click handler
348 if (newPressed == null)
349 newPressed = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
350
351 // Debug.Log("Pressed: " + newPressed);
352
353 float time = Time.unscaledTime;
354
355 if (newPressed == pointerEvent.lastPress)
356 {
357 var diffTime = time - pointerEvent.clickTime;
358 if (diffTime < 0.3f)
359 ++pointerEvent.clickCount;
360 else
361 pointerEvent.clickCount = 1;
362
363 pointerEvent.clickTime = time;
364 }
365 else
366 {
367 pointerEvent.clickCount = 1;
368 }
369
370 pointerEvent.pointerPress = newPressed;
371 pointerEvent.rawPointerPress = currentOverGo;
372
373 pointerEvent.clickTime = time;
374
375 // Save the drag handler as well
376 pointerEvent.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(currentOverGo);
377
378 if (pointerEvent.pointerDrag != null)
379 ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.initializePotentialDrag);
380 }
381
382 // PointerUp notification
383 if (data.ReleasedThisFrame())
384 {
385 // Debug.Log("Executing pressup on: " + pointer.pointerPress);
386 ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerUpHandler);
387
388 // Debug.Log("KeyCode: " + pointer.eventData.keyCode);
389
390 // see if we mouse up on the same element that we clicked on...
391 var pointerUpHandler = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
392
393 // PointerClick and Drop events
394 if (pointerEvent.pointerPress == pointerUpHandler && pointerEvent.eligibleForClick)
395 {
396 ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerClickHandler);
397 }
398 else if (pointerEvent.pointerDrag != null)
399 {
400 ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.dropHandler);
401 }
402
403 pointerEvent.eligibleForClick = false;
404 pointerEvent.pointerPress = null;
405 pointerEvent.rawPointerPress = null;
406
407 if (pointerEvent.pointerDrag != null && pointerEvent.dragging)
408 ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.endDragHandler);
409
410 pointerEvent.dragging = false;
411 pointerEvent.pointerDrag = null;
412
413 // redo pointer enter / exit to refresh state
414 // so that if we moused over somethign that ignored it before
415 // due to having pressed on something else
416 // it now gets it.
417 if (currentOverGo != pointerEvent.pointerEnter)
418 {
419 HandlePointerExitAndEnter(pointerEvent, null);
420 HandlePointerExitAndEnter(pointerEvent, currentOverGo);
421 }
422 }
423 }
424#endregion
425 #region Modified StandaloneInputModule methods
426
427 /// <summary>
428 /// Process all mouse events. This is the same as the StandaloneInputModule version except that
429 /// it takes MouseState as a parameter, allowing it to be used for both Gaze and Mouse
430 /// pointerss.
431 /// </summary>
432 private void ProcessMouseEvent(MouseState mouseData)
433 {
434 var pressed = mouseData.AnyPressesThisFrame();
435 var released = mouseData.AnyReleasesThisFrame();
436
437 var leftButtonData = mouseData.GetButtonState(PointerEventData.InputButton.Left).eventData;
438
439 if (!UseMouse(pressed, released, leftButtonData.buttonData))
440 return;
441
442 // Process the first mouse button fully
443 ProcessMousePress(leftButtonData);
444 ProcessMove(leftButtonData.buttonData);
445 ProcessDrag(leftButtonData.buttonData);
446
447 // Now process right / middle clicks
448 ProcessMousePress(mouseData.GetButtonState(PointerEventData.InputButton.Right).eventData);
449 ProcessDrag(mouseData.GetButtonState(PointerEventData.InputButton.Right).eventData.buttonData);
450 ProcessMousePress(mouseData.GetButtonState(PointerEventData.InputButton.Middle).eventData);
451 ProcessDrag(mouseData.GetButtonState(PointerEventData.InputButton.Middle).eventData.buttonData);
452
453 if (!Mathf.Approximately(leftButtonData.buttonData.scrollDelta.sqrMagnitude, 0.0f))
454 {
455 var scrollHandler = ExecuteEvents.GetEventHandler<IScrollHandler>(leftButtonData.buttonData.pointerCurrentRaycast.gameObject);
456 ExecuteEvents.ExecuteHierarchy(scrollHandler, leftButtonData.buttonData, ExecuteEvents.scrollHandler);
457 }
458 }
459
460 /// <summary>
461 /// Process this InputModule. Same as the StandaloneInputModule version, except that it calls
462 /// ProcessMouseEvent twice, once for gaze pointers, and once for mouse pointers.
463 /// </summary>
464 public override void Process()
465 {
466 bool usedEvent = SendUpdateEventToSelectedObject();
467
468 if (eventSystem.sendNavigationEvents)
469 {
470 if (!usedEvent)
471 usedEvent |= SendMoveEventToSelectedObject();
472
473 if (!usedEvent)
474 SendSubmitEventToSelectedObject();
475 }
476
477 ProcessMouseEvent(GetGazePointerData());
478#if !UNITY_ANDROID
479 ProcessMouseEvent(GetCanvasPointerData());
480#endif
481 }
482 /// <summary>
483 /// Decide if mouse events need to be processed this frame. Same as StandloneInputModule except
484 /// that the IsPointerMoving method from this class is used, instead of the method on PointerEventData
485 /// </summary>
486 private static bool UseMouse(bool pressed, bool released, PointerEventData pointerData)
487 {
488 if (pressed || released || IsPointerMoving(pointerData) || pointerData.IsScrolling())
489 return true;
490
491 return false;
492 }
493 #endregion
494
495
496 /// <summary>
497 /// Convenience function for cloning PointerEventData
498 /// </summary>
499 /// <param name="from">Copy this value</param>
500 /// <param name="to">to this object</param>
501 protected void CopyFromTo(OVRPointerEventData @from, OVRPointerEventData @to)
502 {
503 @to.position = @from.position;
504 @to.delta = @from.delta;
505 @to.scrollDelta = @from.scrollDelta;
506 @to.pointerCurrentRaycast = @from.pointerCurrentRaycast;
507 @to.pointerEnter = @from.pointerEnter;
508 @to.worldSpaceRay = @from.worldSpaceRay;
509 }
510 /// <summary>
511 /// Convenience function for cloning PointerEventData
512 /// </summary>
513 /// <param name="from">Copy this value</param>
514 /// <param name="to">to this object</param>
515 protected new void CopyFromTo(PointerEventData @from, PointerEventData @to)
516 {
517 @to.position = @from.position;
518 @to.delta = @from.delta;
519 @to.scrollDelta = @from.scrollDelta;
520 @to.pointerCurrentRaycast = @from.pointerCurrentRaycast;
521 @to.pointerEnter = @from.pointerEnter;
522 }
523
524
525 // In the following region we extend the PointerEventData system implemented in PointerInputModule
526 // We define an additional dictionary for ray(e.g. gaze) based pointers. Mouse pointers still use the dictionary
527 // in PointerInputModule
528#region PointerEventData pool
529
530 // Pool for OVRRayPointerEventData for ray based pointers
531 protected Dictionary<int, OVRPointerEventData> m_VRRayPointerData = new Dictionary<int, OVRPointerEventData>();
532
533
534 protected bool GetPointerData(int id, out OVRPointerEventData data, bool create)
535 {
536 if (!m_VRRayPointerData.TryGetValue(id, out data) && create)
537 {
538 data = new OVRPointerEventData(eventSystem)
539 {
540 pointerId = id,
541 };
542
543 m_VRRayPointerData.Add(id, data);
544 return true;
545 }
546 return false;
547 }
548
549 /// <summary>
550 /// Clear pointer state for both types of pointer
551 /// </summary>
552 protected new void ClearSelection()
553 {
554 var baseEventData = GetBaseEventData();
555
556 foreach (var pointer in m_PointerData.Values)
557 {
558 // clear all selection
559 HandlePointerExitAndEnter(pointer, null);
560 }
561 foreach (var pointer in m_VRRayPointerData.Values)
562 {
563 // clear all selection
564 HandlePointerExitAndEnter(pointer, null);
565 }
566
567 m_PointerData.Clear();
568 eventSystem.SetSelectedGameObject(null, baseEventData);
569 }
570#endregion
571
572 /// <summary>
573 /// For RectTransform, calculate it's normal in world space
574 /// </summary>
575 static Vector3 GetRectTransformNormal(RectTransform rectTransform)
576 {
577 Vector3[] corners = new Vector3[4];
578 rectTransform.GetWorldCorners(corners);
579 Vector3 BottomEdge = corners[3] - corners[0];
580 Vector3 LeftEdge = corners[1] - corners[0];
581 rectTransform.GetWorldCorners(corners);
582 return Vector3.Cross(BottomEdge, LeftEdge).normalized;
583 }
584
585 private readonly MouseState m_MouseState = new MouseState();
586
587
588 // The following 2 functions are equivalent to PointerInputModule.GetMousePointerEventData but are customized to
589 // get data for ray pointers and canvas mouse pointers.
590
591 /// <summary>
592 /// State for a pointer controlled by a world space ray. E.g. gaze pointer
593 /// </summary>
594 /// <returns></returns>
595 virtual protected MouseState GetGazePointerData()
596 {
597 // Get the OVRRayPointerEventData reference
598 OVRPointerEventData leftData;
599 GetPointerData(kMouseLeftId, out leftData, true );
600 leftData.Reset();
601
602 //Now set the world space ray. This ray is what the user uses to point at UI elements
603 leftData.worldSpaceRay = new Ray(rayTransform.position, rayTransform.forward);
604 leftData.scrollDelta = GetExtraScrollDelta();
605
606 //Populate some default values
607 leftData.button = PointerEventData.InputButton.Left;
608 leftData.useDragThreshold = true;
609 // Perform raycast to find intersections with world
610 eventSystem.RaycastAll(leftData, m_RaycastResultCache);
611 var raycast = FindFirstRaycast(m_RaycastResultCache);
612 leftData.pointerCurrentRaycast = raycast;
613 m_RaycastResultCache.Clear();
614
615 m_Cursor.SetCursorRay(rayTransform);
616
617 OVRRaycaster ovrRaycaster = raycast.module as OVRRaycaster;
618 // We're only interested in intersections from OVRRaycasters
619 if (ovrRaycaster)
620 {
621 // The Unity UI system expects event data to have a screen position
622 // so even though this raycast came from a world space ray we must get a screen
623 // space position for the camera attached to this raycaster for compatability
624 leftData.position = ovrRaycaster.GetScreenPosition(raycast);
625
626 // Find the world position and normal the Graphic the ray intersected
627 RectTransform graphicRect = raycast.gameObject.GetComponent<RectTransform>();
628 if (graphicRect != null)
629 {
630 // Set are gaze indicator with this world position and normal
631 Vector3 worldPos = raycast.worldPosition;
632 Vector3 normal = GetRectTransformNormal(graphicRect);
633 m_Cursor.SetCursorStartDest(rayTransform.position, worldPos, normal);
634 }
635 }
636
637 // Now process physical raycast intersections
638 OVRPhysicsRaycaster physicsRaycaster = raycast.module as OVRPhysicsRaycaster;
639 if (physicsRaycaster)
640 {
641 Vector3 position = raycast.worldPosition;
642
643 if (performSphereCastForGazepointer)
644 {
645 // Here we cast a sphere into the scene rather than a ray. This gives a more accurate depth
646 // for positioning a circular gaze pointer
647 List<RaycastResult> results = new List<RaycastResult>();
648 physicsRaycaster.Spherecast(leftData, results, m_SpherecastRadius);
649 if (results.Count > 0 && results[0].distance < raycast.distance)
650 {
651 position = results[0].worldPosition;
652 }
653 }
654
655 leftData.position = physicsRaycaster.GetScreenPos(raycast.worldPosition);
656
657 m_Cursor.SetCursorStartDest(rayTransform.position, position, raycast.worldNormal);
658 }
659
660 // Stick default data values in right and middle slots for compatability
661
662 // copy the apropriate data into right and middle slots
663 OVRPointerEventData rightData;
664 GetPointerData(kMouseRightId, out rightData, true );
665 CopyFromTo(leftData, rightData);
666 rightData.button = PointerEventData.InputButton.Right;
667
668 OVRPointerEventData middleData;
669 GetPointerData(kMouseMiddleId, out middleData, true );
670 CopyFromTo(leftData, middleData);
671 middleData.button = PointerEventData.InputButton.Middle;
672
673
674 m_MouseState.SetButtonState(PointerEventData.InputButton.Left, GetGazeButtonState(), leftData);
675 m_MouseState.SetButtonState(PointerEventData.InputButton.Right, PointerEventData.FramePressState.NotChanged, rightData);
676 m_MouseState.SetButtonState(PointerEventData.InputButton.Middle, PointerEventData.FramePressState.NotChanged, middleData);
677 return m_MouseState;
678 }
679
680 /// <summary>
681 /// Get state for pointer which is a pointer moving in world space across the surface of a world space canvas.
682 /// </summary>
683 /// <returns></returns>
684 protected MouseState GetCanvasPointerData()
685 {
686 // Get the OVRRayPointerEventData reference
687 PointerEventData leftData;
688 GetPointerData(kMouseLeftId, out leftData, true );
689 leftData.Reset();
690
691 // Setup default values here. Set position to zero because we don't actually know the pointer
692 // positions. Each canvas knows the position of its canvas pointer.
693 leftData.position = Vector2.zero;
694 leftData.scrollDelta = Input.mouseScrollDelta;
695 leftData.button = PointerEventData.InputButton.Left;
696
697 if (activeGraphicRaycaster)
698 {
699 // Let the active raycaster find intersections on its canvas
700 activeGraphicRaycaster.RaycastPointer(leftData, m_RaycastResultCache);
701 var raycast = FindFirstRaycast(m_RaycastResultCache);
702 leftData.pointerCurrentRaycast = raycast;
703 m_RaycastResultCache.Clear();
704
705 OVRRaycaster ovrRaycaster = raycast.module as OVRRaycaster;
706 if (ovrRaycaster) // raycast may not actually contain a result
707 {
708 // The Unity UI system expects event data to have a screen position
709 // so even though this raycast came from a world space ray we must get a screen
710 // space position for the camera attached to this raycaster for compatability
711 Vector2 position = ovrRaycaster.GetScreenPosition(raycast);
712
713 leftData.delta = position - leftData.position;
714 leftData.position = position;
715 }
716 }
717
718 // copy the apropriate data into right and middle slots
719 PointerEventData rightData;
720 GetPointerData(kMouseRightId, out rightData, true );
721 CopyFromTo(leftData, rightData);
722 rightData.button = PointerEventData.InputButton.Right;
723
724 PointerEventData middleData;
725 GetPointerData(kMouseMiddleId, out middleData, true );
726 CopyFromTo(leftData, middleData);
727 middleData.button = PointerEventData.InputButton.Middle;
728
729 m_MouseState.SetButtonState(PointerEventData.InputButton.Left, StateForMouseButton(0), leftData);
730 m_MouseState.SetButtonState(PointerEventData.InputButton.Right, StateForMouseButton(1), rightData);
731 m_MouseState.SetButtonState(PointerEventData.InputButton.Middle, StateForMouseButton(2), middleData);
732 return m_MouseState;
733 }
734
735 /// <summary>
736 /// New version of ShouldStartDrag implemented first in PointerInputModule. This version differs in that
737 /// for ray based pointers it makes a decision about whether a drag should start based on the angular change
738 /// the pointer has made so far, as seen from the camera. This also works when the world space ray is
739 /// translated rather than rotated, since the beginning and end of the movement are considered as angle from
740 /// the same point.
741 /// </summary>
742 private bool ShouldStartDrag(PointerEventData pointerEvent)
743 {
744 if (!pointerEvent.useDragThreshold)
745 return true;
746
747 if (!pointerEvent.IsVRPointer())
748 {
749 // Same as original behaviour for canvas based pointers
750 return (pointerEvent.pressPosition - pointerEvent.position).sqrMagnitude >= eventSystem.pixelDragThreshold * eventSystem.pixelDragThreshold;
751 }
752 else
753 {
754#if UNITY_ANDROID && !UNITY_EDITOR // On android allow swiping to start drag
755 if (useSwipeScroll && ((Vector3)pointerEvent.GetSwipeStart() - Input.mousePosition).magnitude > swipeDragThreshold)
756 {
757 return true;
758 }
759#endif
760 // When it's not a screen space pointer we have to look at the angle it moved rather than the pixels distance
761 // For gaze based pointing screen-space distance moved will always be near 0
762 Vector3 cameraPos = pointerEvent.pressEventCamera.transform.position;
763 Vector3 pressDir = (pointerEvent.pointerPressRaycast.worldPosition - cameraPos).normalized;
764 Vector3 currentDir = (pointerEvent.pointerCurrentRaycast.worldPosition - cameraPos).normalized;
765 return Vector3.Dot(pressDir, currentDir) < Mathf.Cos(Mathf.Deg2Rad * (angleDragThreshold));
766 }
767 }
768
769 /// <summary>
770 /// The purpose of this function is to allow us to switch between using the standard IsPointerMoving
771 /// method for mouse driven pointers, but to always return true when it's a ray based pointer.
772 /// All real-world ray-based input devices are always moving so for simplicity we just return true
773 /// for them.
774 ///
775 /// If PointerEventData.IsPointerMoving was virtual we could just override that in
776 /// OVRRayPointerEventData.
777 /// </summary>
778 /// <param name="pointerEvent"></param>
779 /// <returns></returns>
780 static bool IsPointerMoving(PointerEventData pointerEvent)
781 {
782 if (pointerEvent.IsVRPointer())
783 return true;
784 else
785 return pointerEvent.IsPointerMoving();
786 }
787
788 protected Vector2 SwipeAdjustedPosition(Vector2 originalPosition, PointerEventData pointerEvent)
789 {
790#if UNITY_ANDROID && !UNITY_EDITOR
791 // On android we use the touchpad position (accessed through Input.mousePosition) to modify
792 // the effective cursor position for events related to dragging. This allows the user to
793 // use the touchpad to drag draggable UI elements
794 if (useSwipeScroll)
795 {
796 Vector2 delta = (Vector2)Input.mousePosition - pointerEvent.GetSwipeStart();
797 if (InvertSwipeXAxis)
798 delta.x *= -1;
799 return originalPosition + delta * swipeDragScale;
800 }
801#endif
802 // If not Gear VR or swipe scroll isn't enabled just return original position
803 return originalPosition;
804
805 }
806
807 /// <summary>
808 /// Exactly the same as the code from PointerInputModule, except that we call our own
809 /// IsPointerMoving.
810 ///
811 /// This would also not be necessary if PointerEventData.IsPointerMoving was virtual
812 /// </summary>
813 /// <param name="pointerEvent"></param>
814 protected override void ProcessDrag(PointerEventData pointerEvent)
815 {
816 Vector2 originalPosition = pointerEvent.position;
817 bool moving = IsPointerMoving(pointerEvent);
818 if (moving && pointerEvent.pointerDrag != null
819 && !pointerEvent.dragging
820 && ShouldStartDrag(pointerEvent))
821 {
822 if (pointerEvent.IsVRPointer())
823 {
824 //adjust the position used based on swiping action. Allowing the user to
825 //drag items by swiping on the GearVR touchpad
826 pointerEvent.position = SwipeAdjustedPosition (originalPosition, pointerEvent);
827 }
828 ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.beginDragHandler);
829 pointerEvent.dragging = true;
830 }
831
832 // Drag notification
833 if (pointerEvent.dragging && moving && pointerEvent.pointerDrag != null)
834 {
835 if (pointerEvent.IsVRPointer())
836 {
837 pointerEvent.position = SwipeAdjustedPosition(originalPosition, pointerEvent);
838 }
839 // Before doing drag we should cancel any pointer down state
840 // And clear selection!
841 if (pointerEvent.pointerPress != pointerEvent.pointerDrag)
842 {
843 ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerUpHandler);
844
845 pointerEvent.eligibleForClick = false;
846 pointerEvent.pointerPress = null;
847 pointerEvent.rawPointerPress = null;
848 }
849 ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.dragHandler);
850 }
851 }
852
853 /// <summary>
854 /// Get state of button corresponding to gaze pointer
855 /// </summary>
856 /// <returns></returns>
857 virtual protected PointerEventData.FramePressState GetGazeButtonState()
858 {
859 var pressed = Input.GetKeyDown(gazeClickKey) || OVRInput.GetDown(joyPadClickButton);
860 var released = Input.GetKeyUp(gazeClickKey) || OVRInput.GetUp(joyPadClickButton);
861
862#if UNITY_ANDROID && !UNITY_EDITOR
863 // On Gear VR the mouse button events correspond to touch pad events. We only use these as gaze pointer clicks
864 // on Gear VR because on PC the mouse clicks are used for actual mouse pointer interactions.
865 pressed |= Input.GetMouseButtonDown(0);
866 released |= Input.GetMouseButtonUp(0);
867#endif
868
869 if (pressed && released)
870 return PointerEventData.FramePressState.PressedAndReleased;
871 if (pressed)
872 return PointerEventData.FramePressState.Pressed;
873 if (released)
874 return PointerEventData.FramePressState.Released;
875 return PointerEventData.FramePressState.NotChanged;
876 }
877
878 /// <summary>
879 /// Get extra scroll delta from gamepad
880 /// </summary>
881 protected Vector2 GetExtraScrollDelta()
882 {
883 Vector2 scrollDelta = new Vector2();
884 if (useRightStickScroll)
885 {
886 Vector2 s = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick);
887 if (Mathf.Abs(s.x) < rightStickDeadZone) s.x = 0;
888 if (Mathf.Abs(s.y) < rightStickDeadZone) s.y = 0;
889 scrollDelta = s;
890 }
891 return scrollDelta;
892 }
893 };
894}