2021년 4학년 1학기 기업연계프로젝트2 컴퓨터소프트웨어공학과 <원광투어팀> 팀장 : 송유진 팀원 : 김나영, 이경희, 한유진
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

802 lines
38 KiB

5 years ago
  1. //========= Copyright 2016-2020, HTC Corporation. All rights reserved. ===========
  2. using HTC.UnityPlugin.Utility;
  3. using HTC.UnityPlugin.Vive;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Runtime.InteropServices;
  7. using UnityEngine;
  8. #if VIU_WAVEVR && UNITY_ANDROID
  9. using wvr;
  10. using Object = UnityEngine.Object;
  11. #endif
  12. namespace HTC.UnityPlugin.VRModuleManagement
  13. {
  14. public partial class VRModule : SingletonBehaviour<VRModule>
  15. {
  16. public static readonly bool isWaveVRPluginDetected =
  17. #if VIU_WAVEVR
  18. true;
  19. #else
  20. false;
  21. #endif
  22. public static readonly bool isWaveVRSupported =
  23. #if VIU_WAVEVR_SUPPORT
  24. true;
  25. #else
  26. false;
  27. #endif
  28. }
  29. public sealed class WaveVRModule : VRModule.ModuleBase
  30. {
  31. public override int moduleOrder { get { return (int)DefaultModuleOrder.WaveVR; } }
  32. public override int moduleIndex { get { return (int)VRModuleSelectEnum.WaveVR; } }
  33. #if VIU_WAVEVR && UNITY_ANDROID
  34. private class CameraCreator : VRCameraHook.CameraCreator
  35. {
  36. public override bool shouldActive { get { return s_moduleInstance == null ? false : s_moduleInstance.isActivated; } }
  37. public override void CreateCamera(VRCameraHook hook)
  38. {
  39. if (hook.GetComponent<WaveVR_Render>() == null)
  40. {
  41. hook.gameObject.AddComponent<WaveVR_Render>();
  42. #if VIU_WAVEVR_3_1_3_OR_NEWER && UNITY_EDITOR
  43. wvr.Interop.WVR_PostInit();
  44. #endif
  45. }
  46. if (hook.GetComponent<VivePoseTracker>() == null)
  47. {
  48. hook.gameObject.AddComponent<VivePoseTracker>().viveRole.SetEx(DeviceRole.Hmd);
  49. }
  50. if (hook.GetComponent<AudioListener>() != null)
  51. {
  52. Object.Destroy(hook.GetComponent<AudioListener>());
  53. }
  54. }
  55. }
  56. private class RenderModelCreator : RenderModelHook.RenderModelCreator
  57. {
  58. private uint m_index = INVALID_DEVICE_INDEX;
  59. private GameObject m_model;
  60. private WVR_DeviceType m_loadedHandType;
  61. public override bool shouldActive { get { return s_moduleInstance == null ? false : s_moduleInstance.isActivated; } }
  62. public override void UpdateRenderModel()
  63. {
  64. if (!ChangeProp.Set(ref m_index, hook.GetModelDeviceIndex())) { return; }
  65. var hasValidModel = false;
  66. var handType = default(WVR_DeviceType);
  67. if (VRModule.IsValidDeviceIndex(m_index))
  68. {
  69. if (m_index == VRModule.GetRightControllerDeviceIndex())
  70. {
  71. hasValidModel = true;
  72. handType = WVR_DeviceType.WVR_DeviceType_Controller_Right;
  73. }
  74. else if (m_index == VRModule.GetLeftControllerDeviceIndex())
  75. {
  76. hasValidModel = true;
  77. handType = WVR_DeviceType.WVR_DeviceType_Controller_Left;
  78. }
  79. }
  80. // NOTE: load renderModel only if it hasn't been loaded or user changes handType
  81. if (hasValidModel)
  82. {
  83. if (m_model != null && m_loadedHandType != handType)
  84. {
  85. CleanUpRenderModel();
  86. }
  87. if (m_model == null)
  88. {
  89. // Create WaveVR_ControllerLoader silently (to avoid Start and OnEnable)
  90. var loaderGO = new GameObject("Loader");
  91. loaderGO.transform.SetParent(hook.transform, false);
  92. loaderGO.SetActive(false);
  93. var loader = loaderGO.AddComponent<WaveVR_ControllerLoader>();
  94. loader.TrackPosition = false;
  95. loader.TrackRotation = false;
  96. loader.showIndicator = false;
  97. // Call onLoadController to create model (chould be Finch/Link/Pico/QIYIVR)
  98. switch (handType)
  99. {
  100. case WVR_DeviceType.WVR_DeviceType_Controller_Right:
  101. #if VIU_WAVEVR_3_0_0_OR_NEWER
  102. loader.WhichHand = s_moduleInstance.m_deviceHands[RIGHT_INDEX];
  103. #else
  104. loader.WhichHand = WaveVR_ControllerLoader.ControllerHand.Controller_Right;
  105. #endif
  106. loaderGO.SetActive(true);
  107. if (WaveVR.Instance.getDeviceByType(handType).pose.pose.Is6DoFPose && WaveVR_Controller.IsLeftHanded)
  108. {
  109. loaderGO.SendMessage("onLoadController", WVR_DeviceType.WVR_DeviceType_Controller_Left);
  110. }
  111. else
  112. {
  113. loaderGO.SendMessage("onLoadController", WVR_DeviceType.WVR_DeviceType_Controller_Right);
  114. }
  115. break;
  116. case WVR_DeviceType.WVR_DeviceType_Controller_Left:
  117. #if VIU_WAVEVR_3_0_0_OR_NEWER
  118. loader.WhichHand = s_moduleInstance.m_deviceHands[LEFT_INDEX];
  119. #elif VIU_WAVEVR_2_1_0_OR_NEWER
  120. if (Interop.WVR_GetWaveRuntimeVersion() >= 3 && WaveVR_Controller.IsLeftHanded)
  121. {
  122. loader.WhichHand = WaveVR_ControllerLoader.ControllerHand.Controller_Right;
  123. }
  124. else
  125. {
  126. loader.WhichHand = WaveVR_ControllerLoader.ControllerHand.Controller_Left;
  127. }
  128. #else
  129. loader.WhichHand = WaveVR_ControllerLoader.ControllerHand.Controller_Left;
  130. #endif
  131. loaderGO.SetActive(true);
  132. if (WaveVR.Instance.getDeviceByType(handType).pose.pose.Is6DoFPose && WaveVR_Controller.IsLeftHanded)
  133. {
  134. loaderGO.SendMessage("onLoadController", WVR_DeviceType.WVR_DeviceType_Controller_Right);
  135. }
  136. else
  137. {
  138. loaderGO.SendMessage("onLoadController", WVR_DeviceType.WVR_DeviceType_Controller_Left);
  139. }
  140. break;
  141. }
  142. // Find transform that only contains controller model (include animator, exclude PoseTracker/Beam/UIPointer)
  143. // and remove other unnecessary objects
  144. var ctrllerActions = FindWaveVRControllerActionsObjInChildren();
  145. if (ctrllerActions != null)
  146. {
  147. ctrllerActions.transform.SetParent(hook.transform, false);
  148. ctrllerActions.transform.SetAsFirstSibling();
  149. for (int i = hook.transform.childCount - 1; i >= 1; --i)
  150. {
  151. Object.Destroy(hook.transform.GetChild(i).gameObject);
  152. }
  153. ctrllerActions.gameObject.SetActive(true);
  154. m_model = ctrllerActions.gameObject;
  155. }
  156. else
  157. {
  158. Debug.LogWarning("FindWaveVRControllerActionsObjInChildren failed");
  159. for (int i = hook.transform.childCount - 1; i >= 0; --i)
  160. {
  161. Object.Destroy(hook.transform.GetChild(i).gameObject);
  162. }
  163. }
  164. m_loadedHandType = handType;
  165. }
  166. m_model.SetActive(true);
  167. }
  168. else
  169. {
  170. if (m_model != null)
  171. {
  172. m_model.SetActive(false);
  173. }
  174. }
  175. }
  176. public override void CleanUpRenderModel()
  177. {
  178. if (m_model != null)
  179. {
  180. Object.Destroy(m_model);
  181. m_model = null;
  182. }
  183. }
  184. // FIXME: This is for finding Controller model with animator, is reliable?
  185. private Transform FindWaveVRControllerActionsObjInChildren()
  186. {
  187. var nodes = new List<Transform>();
  188. nodes.Add(hook.transform);
  189. for (int i = 0; i < nodes.Count; ++i)
  190. {
  191. var parent = nodes[i];
  192. for (int j = 0, jmax = parent.childCount; j < jmax; ++j)
  193. {
  194. var child = parent.GetChild(j);
  195. nodes.Add(child);
  196. if (child.GetComponent<WaveVR_PoseTrackerManager>() != null) { continue; }
  197. if (child.GetComponent<WaveVR_Beam>() != null) { continue; }
  198. if (child.GetComponent<WaveVR_ControllerPointer>() != null) { continue; }
  199. if (child.GetComponent<WaveVR_ControllerLoader>() != null) { continue; }
  200. return child;
  201. }
  202. }
  203. return null;
  204. }
  205. }
  206. private const uint DEVICE_COUNT = 3;
  207. private const uint HEAD_INDEX = 0;
  208. private const uint RIGHT_INDEX = 1;
  209. private const uint LEFT_INDEX = 2;
  210. public static readonly Vector3 RIGHT_ARM_MULTIPLIER = new Vector3(1f, 1f, 1f);
  211. public static readonly Vector3 LEFT_ARM_MULTIPLIER = new Vector3(-1f, 1f, 1f);
  212. public const float DEFAULT_ELBOW_BEND_RATIO = 0.6f;
  213. public const float MIN_EXTENSION_ANGLE = 7.0f;
  214. public const float MAX_EXTENSION_ANGLE = 60.0f;
  215. public const float EXTENSION_WEIGHT = 0.4f;
  216. private static WaveVRModule s_moduleInstance;
  217. private static readonly WVR_DeviceType[] s_index2type;
  218. private static readonly uint[] s_type2index;
  219. private static readonly VRModuleDeviceClass[] s_type2class;
  220. private IVRModuleDeviceStateRW m_headState;
  221. private IVRModuleDeviceStateRW m_rightState;
  222. private IVRModuleDeviceStateRW m_leftState;
  223. private WaveVR_ControllerLoader.ControllerHand[] m_deviceHands = new WaveVR_ControllerLoader.ControllerHand[DEVICE_COUNT];
  224. #region 6Dof Controller Simulation
  225. private enum Simulate6DoFControllerMode
  226. {
  227. KeyboardWASD,
  228. KeyboardModifierTrackpad,
  229. }
  230. private static Simulate6DoFControllerMode s_simulationMode = Simulate6DoFControllerMode.KeyboardWASD;
  231. private static Vector3[] s_simulatedCtrlPosArray;
  232. #endregion
  233. static WaveVRModule()
  234. {
  235. s_index2type = new WVR_DeviceType[DEVICE_COUNT];
  236. s_index2type[0] = WVR_DeviceType.WVR_DeviceType_HMD;
  237. s_index2type[1] = WVR_DeviceType.WVR_DeviceType_Controller_Right;
  238. s_index2type[2] = WVR_DeviceType.WVR_DeviceType_Controller_Left;
  239. s_type2index = new uint[EnumUtils.GetMaxValue(typeof(WVR_DeviceType)) + 1];
  240. for (int i = 0; i < s_type2index.Length; ++i) { s_type2index[i] = INVALID_DEVICE_INDEX; }
  241. s_type2index[(int)WVR_DeviceType.WVR_DeviceType_HMD] = 0u;
  242. s_type2index[(int)WVR_DeviceType.WVR_DeviceType_Controller_Right] = 1u;
  243. s_type2index[(int)WVR_DeviceType.WVR_DeviceType_Controller_Left] = 2u;
  244. s_type2class = new VRModuleDeviceClass[s_type2index.Length];
  245. for (int i = 0; i < s_type2class.Length; ++i) { s_type2class[i] = VRModuleDeviceClass.Invalid; }
  246. s_type2class[(int)WVR_DeviceType.WVR_DeviceType_HMD] = VRModuleDeviceClass.HMD;
  247. s_type2class[(int)WVR_DeviceType.WVR_DeviceType_Controller_Right] = VRModuleDeviceClass.Controller;
  248. s_type2class[(int)WVR_DeviceType.WVR_DeviceType_Controller_Left] = VRModuleDeviceClass.Controller;
  249. s_simulatedCtrlPosArray = new Vector3[s_type2index.Length];
  250. }
  251. public override bool ShouldActiveModule()
  252. {
  253. #if VIU_WAVEVR_3_1_3_OR_NEWER && UNITY_EDITOR
  254. return UnityEditor.EditorPrefs.GetBool("WaveVR/DirectPreview/Enable Direct Preview", false);
  255. #elif !VIU_WAVEVR_2_1_0_OR_NEWER && UNITY_EDITOR
  256. return false;
  257. #else
  258. return VIUSettings.activateWaveVRModule;
  259. #endif
  260. }
  261. public override void OnActivated()
  262. {
  263. if (Object.FindObjectOfType<WaveVR_Init>() == null)
  264. {
  265. VRModule.Instance.gameObject.AddComponent<WaveVR_Init>();
  266. }
  267. #if !UNITY_EDITOR && VIU_WAVEVR_3_1_0_OR_NEWER
  268. if (Object.FindObjectOfType<WaveVR_ButtonList>() == null)
  269. {
  270. VRModule.Instance.gameObject.AddComponent<WaveVR_ButtonList>();
  271. var buttonList = VRModule.Instance.gameObject.GetComponent<WaveVR_ButtonList>();
  272. if (buttonList != null)
  273. {
  274. buttonList.HmdButtons = new List<WaveVR_ButtonList.EHmdButtons>()
  275. {
  276. WaveVR_ButtonList.EHmdButtons.Enter
  277. };
  278. buttonList.DominantButtons = new List<WaveVR_ButtonList.EControllerButtons>()
  279. {
  280. WaveVR_ButtonList.EControllerButtons.Grip,
  281. WaveVR_ButtonList.EControllerButtons.Menu,
  282. WaveVR_ButtonList.EControllerButtons.Touchpad,
  283. WaveVR_ButtonList.EControllerButtons.Trigger
  284. };
  285. buttonList.NonDominantButtons = new List<WaveVR_ButtonList.EControllerButtons>()
  286. {
  287. WaveVR_ButtonList.EControllerButtons.Grip,
  288. WaveVR_ButtonList.EControllerButtons.Menu,
  289. WaveVR_ButtonList.EControllerButtons.Touchpad,
  290. WaveVR_ButtonList.EControllerButtons.Trigger
  291. };
  292. }
  293. }
  294. #elif !UNITY_EDITOR && VIU_WAVEVR_3_0_0_OR_NEWER
  295. if (Object.FindObjectOfType<WaveVR_ButtonList>() == null)
  296. {
  297. VRModule.Instance.gameObject.AddComponent<WaveVR_ButtonList>();
  298. var buttonList = VRModule.Instance.gameObject.GetComponent<WaveVR_ButtonList>();
  299. if (buttonList != null)
  300. {
  301. buttonList.HmdButtons = new List<WaveVR_ButtonList.EButtons>()
  302. {
  303. WaveVR_ButtonList.EButtons.HMDEnter
  304. };
  305. buttonList.DominantButtons = new List<WaveVR_ButtonList.EButtons>()
  306. {
  307. WaveVR_ButtonList.EButtons.Grip,
  308. WaveVR_ButtonList.EButtons.Menu,
  309. WaveVR_ButtonList.EButtons.Touchpad,
  310. WaveVR_ButtonList.EButtons.Trigger
  311. };
  312. buttonList.NonDominantButtons = new List<WaveVR_ButtonList.EButtons>()
  313. {
  314. WaveVR_ButtonList.EButtons.Grip,
  315. WaveVR_ButtonList.EButtons.Menu,
  316. WaveVR_ButtonList.EButtons.Touchpad,
  317. WaveVR_ButtonList.EButtons.Trigger
  318. };
  319. }
  320. }
  321. #endif
  322. EnsureDeviceStateLength(DEVICE_COUNT);
  323. UpdateTrackingSpaceType();
  324. s_moduleInstance = this;
  325. WaveVR_Utils.Event.Listen(WaveVR_Utils.Event.NEW_POSES, OnNewPoses);
  326. }
  327. public override void OnDeactivated()
  328. {
  329. WaveVR_Utils.Event.Remove(WaveVR_Utils.Event.NEW_POSES, OnNewPoses);
  330. m_headState = null;
  331. m_rightState = null;
  332. m_leftState = null;
  333. s_moduleInstance = null;
  334. }
  335. public override void UpdateTrackingSpaceType()
  336. {
  337. if (WaveVR_Render.Instance != null)
  338. {
  339. // Only effected when origin is OnHead or OnGround
  340. // This way you can manually set WaveVR_Render origin to other value lik OnTrackingObserver or OnHead_3DoF
  341. if (VRModule.trackingSpaceType == VRModuleTrackingSpaceType.RoomScale)
  342. {
  343. if (WaveVR_Render.Instance.origin == WVR_PoseOriginModel.WVR_PoseOriginModel_OriginOnHead)
  344. {
  345. WaveVR_Render.Instance.origin = WVR_PoseOriginModel.WVR_PoseOriginModel_OriginOnGround;
  346. }
  347. }
  348. else if (VRModule.trackingSpaceType == VRModuleTrackingSpaceType.Stationary)
  349. {
  350. if (WaveVR_Render.Instance.origin == WVR_PoseOriginModel.WVR_PoseOriginModel_OriginOnGround)
  351. {
  352. WaveVR_Render.Instance.origin = WVR_PoseOriginModel.WVR_PoseOriginModel_OriginOnHead;
  353. }
  354. }
  355. }
  356. }
  357. public override void Update()
  358. {
  359. var rightDevice = GetWVRControllerDevice(WVR_DeviceType.WVR_DeviceType_Controller_Right);
  360. UpdateDeviceInput(1, rightDevice);
  361. var leftDevice = GetWVRControllerDevice(WVR_DeviceType.WVR_DeviceType_Controller_Left);
  362. UpdateDeviceInput(2, leftDevice);
  363. ProcessDeviceInputChanged();
  364. }
  365. private WaveVR_Controller.Device GetWVRControllerDevice(WVR_DeviceType deviceType)
  366. {
  367. switch (deviceType)
  368. {
  369. case WVR_DeviceType.WVR_DeviceType_Controller_Right:
  370. return WaveVR_Controller.Input(WaveVR_Controller.IsLeftHanded ? WVR_DeviceType.WVR_DeviceType_Controller_Left : WVR_DeviceType.WVR_DeviceType_Controller_Right);
  371. case WVR_DeviceType.WVR_DeviceType_Controller_Left:
  372. return WaveVR_Controller.Input(WaveVR_Controller.IsLeftHanded ? WVR_DeviceType.WVR_DeviceType_Controller_Right : WVR_DeviceType.WVR_DeviceType_Controller_Left);
  373. default:
  374. return null;
  375. }
  376. }
  377. private WaveVR.Device GetWVRDevice(WVR_DeviceType deviceType)
  378. {
  379. switch (deviceType)
  380. {
  381. case WVR_DeviceType.WVR_DeviceType_HMD:
  382. return WaveVR.Instance.getDeviceByType(deviceType);
  383. case WVR_DeviceType.WVR_DeviceType_Controller_Right:
  384. return WaveVR.Instance.getDeviceByType(WaveVR_Controller.IsLeftHanded ? WVR_DeviceType.WVR_DeviceType_Controller_Left : WVR_DeviceType.WVR_DeviceType_Controller_Right);
  385. case WVR_DeviceType.WVR_DeviceType_Controller_Left:
  386. return WaveVR.Instance.getDeviceByType(WaveVR_Controller.IsLeftHanded ? WVR_DeviceType.WVR_DeviceType_Controller_Right : WVR_DeviceType.WVR_DeviceType_Controller_Left);
  387. default:
  388. return null;
  389. }
  390. }
  391. private void UpdateDeviceInput(uint deviceIndex, WaveVR_Controller.Device deviceInput)
  392. {
  393. #if VIU_WAVEVR_2_1_0_OR_NEWER
  394. const WVR_InputId digitalTrggerBumpID = WVR_InputId.WVR_InputId_Alias1_Digital_Trigger;
  395. #else
  396. const WVR_InputId digitalTrggerBumpID = WVR_InputId.WVR_InputId_Alias1_Bumper;
  397. #endif
  398. IVRModuleDeviceState prevState;
  399. IVRModuleDeviceStateRW currState;
  400. if (!TryGetValidDeviceState(deviceIndex, out prevState, out currState) || !deviceInput.connected) { return; }
  401. if (deviceInput != null)
  402. {
  403. var systemPressed = deviceInput.GetPress(WVR_InputId.WVR_InputId_Alias1_System);
  404. var menuPressed = deviceInput.GetPress(WVR_InputId.WVR_InputId_Alias1_Menu);
  405. var triggerPressed = deviceInput.GetPress(WVR_InputId.WVR_InputId_Alias1_Trigger);
  406. var digitalTriggerPressed = deviceInput.GetPress(digitalTrggerBumpID);
  407. var gripPressed = deviceInput.GetPress(WVR_InputId.WVR_InputId_Alias1_Grip);
  408. var touchpadPressed = deviceInput.GetPress(WVR_InputId.WVR_InputId_Alias1_Touchpad);
  409. var dpadLeftPressed = deviceInput.GetPress(WVR_InputId.WVR_InputId_Alias1_DPad_Left);
  410. var dpadUpPressed = deviceInput.GetPress(WVR_InputId.WVR_InputId_Alias1_DPad_Up);
  411. var dpadRightPressed = deviceInput.GetPress(WVR_InputId.WVR_InputId_Alias1_DPad_Right);
  412. var dpadDownPressed = deviceInput.GetPress(WVR_InputId.WVR_InputId_Alias1_DPad_Down);
  413. currState.SetButtonPress(VRModuleRawButton.System, systemPressed);
  414. currState.SetButtonPress(VRModuleRawButton.ApplicationMenu, menuPressed);
  415. currState.SetButtonPress(VRModuleRawButton.Touchpad, touchpadPressed || dpadLeftPressed || dpadUpPressed || dpadRightPressed || dpadDownPressed);
  416. currState.SetButtonPress(VRModuleRawButton.Trigger, triggerPressed || digitalTriggerPressed);
  417. currState.SetButtonPress(VRModuleRawButton.Grip, gripPressed);
  418. currState.SetButtonPress(VRModuleRawButton.DPadLeft, dpadLeftPressed);
  419. currState.SetButtonPress(VRModuleRawButton.DPadUp, dpadUpPressed);
  420. currState.SetButtonPress(VRModuleRawButton.DPadRight, dpadRightPressed);
  421. currState.SetButtonPress(VRModuleRawButton.DPadDown, dpadDownPressed);
  422. var systemTouched = deviceInput.GetTouch(WVR_InputId.WVR_InputId_Alias1_System);
  423. var menuTouched = deviceInput.GetTouch(WVR_InputId.WVR_InputId_Alias1_Menu);
  424. var triggerTouched = deviceInput.GetTouch(WVR_InputId.WVR_InputId_Alias1_Trigger);
  425. var digitalTriggerTouched = deviceInput.GetTouch(digitalTrggerBumpID);
  426. var gripTouched = deviceInput.GetTouch(WVR_InputId.WVR_InputId_Alias1_Grip);
  427. var touchpadTouched = deviceInput.GetTouch(WVR_InputId.WVR_InputId_Alias1_Touchpad);
  428. var dpadLeftTouched = deviceInput.GetTouch(WVR_InputId.WVR_InputId_Alias1_DPad_Left);
  429. var dpadUpTouched = deviceInput.GetTouch(WVR_InputId.WVR_InputId_Alias1_DPad_Up);
  430. var dpadRightTouched = deviceInput.GetTouch(WVR_InputId.WVR_InputId_Alias1_DPad_Right);
  431. var dpadDownTouched = deviceInput.GetTouch(WVR_InputId.WVR_InputId_Alias1_DPad_Down);
  432. currState.SetButtonTouch(VRModuleRawButton.System, systemTouched);
  433. currState.SetButtonTouch(VRModuleRawButton.ApplicationMenu, menuTouched);
  434. currState.SetButtonTouch(VRModuleRawButton.Touchpad, touchpadTouched || dpadLeftTouched || dpadUpTouched || dpadRightTouched || dpadDownTouched);
  435. currState.SetButtonTouch(VRModuleRawButton.Trigger, triggerTouched || digitalTriggerTouched);
  436. currState.SetButtonTouch(VRModuleRawButton.Grip, gripTouched);
  437. currState.SetButtonTouch(VRModuleRawButton.DPadLeft, dpadLeftTouched);
  438. currState.SetButtonTouch(VRModuleRawButton.DPadUp, dpadUpTouched);
  439. currState.SetButtonTouch(VRModuleRawButton.DPadRight, dpadRightTouched);
  440. currState.SetButtonTouch(VRModuleRawButton.DPadDown, dpadDownTouched);
  441. var triggerAxis = deviceInput.GetAxis(WVR_InputId.WVR_InputId_Alias1_Trigger);
  442. var touchAxis = deviceInput.GetAxis(WVR_InputId.WVR_InputId_Alias1_Touchpad);
  443. currState.SetAxisValue(VRModuleRawAxis.Trigger, triggerAxis.x);
  444. currState.SetAxisValue(VRModuleRawAxis.TouchpadX, touchAxis.x);
  445. currState.SetAxisValue(VRModuleRawAxis.TouchpadY, touchAxis.y);
  446. }
  447. else
  448. {
  449. currState.buttonPressed = 0u;
  450. currState.buttonTouched = 0u;
  451. currState.ResetAxisValues();
  452. }
  453. }
  454. private IVRModuleDeviceStateRW UpdateDevicePose(uint deviceIndex, WaveVR.Device content)
  455. {
  456. IVRModuleDeviceState prevState;
  457. IVRModuleDeviceStateRW currState;
  458. EnsureValidDeviceState(deviceIndex, out prevState, out currState);
  459. var deviceConnected = content.type == WVR_DeviceType.WVR_DeviceType_HMD ? true : content.connected;
  460. if (!deviceConnected)
  461. {
  462. if (prevState.isConnected)
  463. {
  464. currState.Reset();
  465. switch (content.type)
  466. {
  467. case WVR_DeviceType.WVR_DeviceType_HMD: m_headState = null; break;
  468. case WVR_DeviceType.WVR_DeviceType_Controller_Right: m_rightState = null; break;
  469. case WVR_DeviceType.WVR_DeviceType_Controller_Left: m_leftState = null; break;
  470. }
  471. }
  472. }
  473. else
  474. {
  475. if (!prevState.isConnected)
  476. {
  477. string renderModelName;
  478. if (!TryGetWVRStringParameter(s_index2type[(int)deviceIndex], "GetRenderModelName", out renderModelName))
  479. {
  480. renderModelName = "wvr_unknown_device";
  481. }
  482. currState.isConnected = true;
  483. currState.deviceClass = s_type2class[(int)content.type];
  484. currState.serialNumber = content.type.ToString();
  485. currState.modelNumber = renderModelName;
  486. currState.renderModelName = renderModelName;
  487. currState.input2DType = VRModuleInput2DType.TouchpadOnly;
  488. SetupKnownDeviceModel(currState);
  489. }
  490. // update pose
  491. var devicePose = content.pose.pose;
  492. currState.velocity = new Vector3(devicePose.Velocity.v0, devicePose.Velocity.v1, -devicePose.Velocity.v2);
  493. currState.angularVelocity = new Vector3(-devicePose.AngularVelocity.v0, -devicePose.AngularVelocity.v1, devicePose.AngularVelocity.v2);
  494. var rigidTransform = content.rigidTransform;
  495. currState.position = rigidTransform.pos;
  496. currState.rotation = rigidTransform.rot;
  497. currState.isPoseValid = devicePose.IsValidPose;
  498. }
  499. return currState;
  500. }
  501. private void OnNewPoses(params object[] args)
  502. {
  503. if (WaveVR.Instance == null) { return; }
  504. FlushDeviceState();
  505. var headDevice = GetWVRDevice(WVR_DeviceType.WVR_DeviceType_HMD);
  506. m_headState = UpdateDevicePose(0, headDevice);
  507. var rightDevice = GetWVRDevice(WVR_DeviceType.WVR_DeviceType_Controller_Right);
  508. m_rightState = UpdateDevicePose(1, rightDevice);
  509. var leftDevice = GetWVRDevice(WVR_DeviceType.WVR_DeviceType_Controller_Left);
  510. m_leftState = UpdateDevicePose(2, leftDevice);
  511. #if VIU_WAVEVR_3_0_0_OR_NEWER
  512. if (WaveVR_Controller.IsLeftHanded)
  513. {
  514. m_deviceHands[RIGHT_INDEX] = WaveVR_ControllerLoader.ControllerHand.Non_Dominant;
  515. m_deviceHands[LEFT_INDEX] = WaveVR_ControllerLoader.ControllerHand.Dominant;
  516. }
  517. else
  518. {
  519. m_deviceHands[RIGHT_INDEX] = WaveVR_ControllerLoader.ControllerHand.Dominant;
  520. m_deviceHands[LEFT_INDEX] = WaveVR_ControllerLoader.ControllerHand.Non_Dominant;
  521. }
  522. #endif
  523. if (m_rightState != null && !rightDevice.pose.pose.Is6DoFPose)
  524. {
  525. ApplyVirtualArmAndSimulateInput(m_rightState, m_headState, RIGHT_ARM_MULTIPLIER);
  526. }
  527. if (m_leftState != null && !leftDevice.pose.pose.Is6DoFPose)
  528. {
  529. ApplyVirtualArmAndSimulateInput(m_leftState, m_headState, LEFT_ARM_MULTIPLIER);
  530. }
  531. ProcessConnectedDeviceChanged();
  532. ProcessDevicePoseChanged();
  533. }
  534. // FIXME: WVR_IsInputFocusCapturedBySystem currently not implemented yet
  535. //public override bool HasInputFocus()
  536. //{
  537. // return m_hasInputFocus;
  538. //}
  539. public override uint GetRightControllerDeviceIndex() { return RIGHT_INDEX; }
  540. public override uint GetLeftControllerDeviceIndex() { return LEFT_INDEX; }
  541. private void ApplyVirtualArmAndSimulateInput(IVRModuleDeviceStateRW ctrlState, IVRModuleDeviceStateRW headState, Vector3 handSideMultiplier)
  542. {
  543. if (!ctrlState.isConnected) { return; }
  544. if (!VIUSettings.waveVRAddVirtualArmTo3DoFController && !VIUSettings.simulateWaveVR6DofController) { return; }
  545. var deviceType = (int)s_index2type[ctrlState.deviceIndex];
  546. #if !UNITY_EDITOR
  547. if (Interop.WVR_GetDegreeOfFreedom((WVR_DeviceType)deviceType) == WVR_NumDoF.WVR_NumDoF_6DoF) { return; }
  548. #elif VIU_WAVEVR_3_1_3_OR_NEWER && UNITY_EDITOR
  549. if (!WaveVR.EnableSimulator || WVR_DirectPreview.WVR_GetDegreeOfFreedom_S(0) == (int)WVR_NumDoF.WVR_NumDoF_6DoF) { return; }
  550. #elif VIU_WAVEVR_3_1_0_OR_NEWER && UNITY_EDITOR
  551. if (!WaveVR.EnableSimulator || WVR_Simulator.WVR_GetDegreeOfFreedom_S(0) == (int)WVR_NumDoF.WVR_NumDoF_6DoF) { return; }
  552. #elif VIU_WAVEVR_2_1_0_OR_NEWER && UNITY_EDITOR
  553. if (!WaveVR.Instance.isSimulatorOn || WaveVR_Utils.WVR_GetDegreeOfFreedom_S() == (int)WVR_NumDoF.WVR_NumDoF_6DoF) { return; }
  554. #endif
  555. if (VIUSettings.simulateWaveVR6DofController)
  556. {
  557. if (Input.GetKeyDown(KeyCode.Alpha1)) { s_simulationMode = Simulate6DoFControllerMode.KeyboardWASD; }
  558. if (Input.GetKeyDown(KeyCode.Alpha2)) { s_simulationMode = Simulate6DoFControllerMode.KeyboardModifierTrackpad; }
  559. if (Input.GetKeyDown(KeyCode.BackQuote)) { s_simulatedCtrlPosArray[deviceType] = Vector3.zero; }
  560. var deltaMove = Time.unscaledDeltaTime;
  561. var rotY = Quaternion.Euler(0f, ctrlState.rotation.eulerAngles.y, 0f);
  562. var moveForward = rotY * Vector3.forward;
  563. var moveRight = rotY * Vector3.right;
  564. switch (s_simulationMode)
  565. {
  566. case Simulate6DoFControllerMode.KeyboardWASD:
  567. {
  568. if (Input.GetKey(KeyCode.D)) { s_simulatedCtrlPosArray[deviceType] += moveRight * deltaMove; }
  569. if (Input.GetKey(KeyCode.A)) { s_simulatedCtrlPosArray[deviceType] -= moveRight * deltaMove; }
  570. if (Input.GetKey(KeyCode.E)) { s_simulatedCtrlPosArray[deviceType] += Vector3.up * deltaMove; }
  571. if (Input.GetKey(KeyCode.Q)) { s_simulatedCtrlPosArray[deviceType] -= Vector3.up * deltaMove; }
  572. if (Input.GetKey(KeyCode.W)) { s_simulatedCtrlPosArray[deviceType] += moveForward * deltaMove; }
  573. if (Input.GetKey(KeyCode.S)) { s_simulatedCtrlPosArray[deviceType] -= moveForward * deltaMove; }
  574. break;
  575. }
  576. case Simulate6DoFControllerMode.KeyboardModifierTrackpad:
  577. {
  578. float speedModifier = 2f;
  579. float x = ctrlState.GetAxisValue(VRModuleRawAxis.TouchpadX) * speedModifier;
  580. float y = ctrlState.GetAxisValue(VRModuleRawAxis.TouchpadY) * speedModifier;
  581. if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
  582. {
  583. s_simulatedCtrlPosArray[deviceType] += x * moveRight * deltaMove;
  584. s_simulatedCtrlPosArray[deviceType] += y * moveForward * deltaMove;
  585. }
  586. if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
  587. {
  588. s_simulatedCtrlPosArray[deviceType] += x * moveRight * deltaMove;
  589. s_simulatedCtrlPosArray[deviceType] += y * Vector3.up * deltaMove;
  590. }
  591. break;
  592. }
  593. }
  594. }
  595. if (VIUSettings.waveVRAddVirtualArmTo3DoFController)
  596. {
  597. var neckPose = new RigidPose(s_simulatedCtrlPosArray[deviceType], Quaternion.identity) * GetNeckPose(headState.pose);
  598. ctrlState.position = GetControllerPositionWithVirtualArm(neckPose, ctrlState.rotation, handSideMultiplier);
  599. }
  600. else
  601. {
  602. ctrlState.position += s_simulatedCtrlPosArray[deviceType];
  603. }
  604. }
  605. private static RigidPose GetNeckPose(RigidPose headPose)
  606. {
  607. var headForward = headPose.forward;
  608. return new RigidPose(headPose.pos + VIUSettings.waveVRVirtualNeckPosition, Quaternion.FromToRotation(Vector3.forward, new Vector3(headForward.x, 0f, headForward.z)));
  609. }
  610. private static float GetExtensionRatio(Vector3 v)
  611. {
  612. var xAngle = 90f - Vector3.Angle(v, Vector3.up);
  613. return Mathf.Clamp01(Mathf.InverseLerp(MIN_EXTENSION_ANGLE, MAX_EXTENSION_ANGLE, xAngle));
  614. }
  615. private static Quaternion GetLerpRotation(Quaternion xyRotation, float extensionRatio)
  616. {
  617. float totalAngle = Quaternion.Angle(xyRotation, Quaternion.identity);
  618. float lerpSuppresion = 1.0f - Mathf.Pow(totalAngle / 180.0f, 6.0f);
  619. float inverseElbowBendRatio = 1.0f - DEFAULT_ELBOW_BEND_RATIO;
  620. float lerpValue = inverseElbowBendRatio + DEFAULT_ELBOW_BEND_RATIO * extensionRatio * EXTENSION_WEIGHT;
  621. lerpValue *= lerpSuppresion;
  622. return Quaternion.Lerp(Quaternion.identity, xyRotation, lerpValue);
  623. }
  624. private static Vector3 GetControllerPositionWithVirtualArm(RigidPose neckPose, Quaternion ctrlRot, Vector3 sideMultiplier)
  625. {
  626. var localCtrlForward = (Quaternion.Inverse(neckPose.rot) * ctrlRot) * Vector3.forward;
  627. var localCtrlXYRot = Quaternion.FromToRotation(Vector3.forward, localCtrlForward);
  628. var extensionRatio = GetExtensionRatio(localCtrlForward);
  629. var lerpRotation = GetLerpRotation(localCtrlXYRot, extensionRatio);
  630. var elbowPose = new RigidPose(
  631. Vector3.Scale(VIUSettings.waveVRVirtualElbowRestPosition, sideMultiplier) + Vector3.Scale(VIUSettings.waveVRVirtualArmExtensionOffset, sideMultiplier) * extensionRatio,
  632. Quaternion.Inverse(lerpRotation) * localCtrlXYRot);
  633. var wristPose = new RigidPose(
  634. Vector3.Scale(VIUSettings.waveVRVirtualWristRestPosition, sideMultiplier),
  635. lerpRotation);
  636. var palmPose = new RigidPose(
  637. Vector3.Scale(VIUSettings.waveVRVirtualHandRestPosition, sideMultiplier),
  638. Quaternion.identity);
  639. var finalCtrlPose = neckPose * elbowPose * wristPose * palmPose;
  640. return finalCtrlPose.pos;
  641. }
  642. public override void TriggerViveControllerHaptic(uint deviceIndex, ushort durationMicroSec = 500)
  643. {
  644. var deviceInput = WaveVR_Controller.Input(s_index2type[deviceIndex]);
  645. if (deviceInput != null)
  646. {
  647. deviceInput.TriggerHapticPulse(durationMicroSec);
  648. }
  649. }
  650. private bool TryGetWVRStringParameter(WVR_DeviceType device, string paramName, out string result)
  651. {
  652. result = default(string);
  653. var resultLen = 0u;
  654. try
  655. {
  656. const int resultMaxLen = 128;
  657. var resultBuffer = resultMaxLen;
  658. var resultPtr = Marshal.AllocHGlobal(resultBuffer);
  659. var paramNamePtr = Marshal.StringToHGlobalAnsi(paramName);
  660. resultLen = Interop.WVR_GetParameters(device, paramNamePtr, resultPtr, resultMaxLen);
  661. if (resultLen > 0u)
  662. {
  663. result = Marshal.PtrToStringAnsi(resultPtr);
  664. }
  665. }
  666. catch (Exception e)
  667. {
  668. Debug.LogException(e);
  669. }
  670. return resultLen > 0u;
  671. }
  672. #if VIU_WAVEVR_3_1_0_OR_NEWER
  673. public override void TriggerHapticVibration(uint deviceIndex, float durationSeconds = 0.01f, float frequency = 85, float amplitude = 0.125f, float startSecondsFromNow = 0)
  674. {
  675. var deviceInput = WaveVR_Controller.Input(s_index2type[deviceIndex]);
  676. var intensity = default(WVR_Intensity);
  677. if (deviceInput != null)
  678. {
  679. if (0 <= amplitude || amplitude <= 0.2)
  680. {
  681. intensity = WVR_Intensity.WVR_Intensity_Weak;
  682. }
  683. else if (0.2 < amplitude || amplitude <= 0.4)
  684. {
  685. intensity = WVR_Intensity.WVR_Intensity_Light;
  686. }
  687. else if (0.4 < amplitude || amplitude <= 0.6)
  688. {
  689. intensity = WVR_Intensity.WVR_Intensity_Normal;
  690. }
  691. else if (0.6 < amplitude || amplitude <= 0.8)
  692. {
  693. intensity = WVR_Intensity.WVR_Intensity_Strong;
  694. }
  695. else if (0.8 < amplitude || amplitude <= 1)
  696. {
  697. intensity = WVR_Intensity.WVR_Intensity_Severe;
  698. }
  699. }
  700. Interop.WVR_TriggerVibration(deviceInput.DeviceType, WVR_InputId.WVR_InputId_Alias1_Touchpad, (uint)(durationSeconds * 1000000), (uint)frequency, intensity);
  701. }
  702. #endif
  703. #endif
  704. }
  705. }