OVRInputModule.cs 37 KB

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