Hand.cs 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686
  1. //======= Copyright (c) Valve Corporation, All rights reserved. ===============
  2. //
  3. // Purpose: The hands used by the player in the vr interaction system
  4. //
  5. //=============================================================================
  6. using UnityEngine;
  7. using System;
  8. using System.Collections;
  9. using System.Collections.Generic;
  10. using System.Collections.ObjectModel;
  11. using UnityEngine.Events;
  12. using System.Threading;
  13. namespace Valve.VR.InteractionSystem
  14. {
  15. //-------------------------------------------------------------------------
  16. // Links with an appropriate SteamVR controller and facilitates
  17. // interactions with objects in the virtual world.
  18. //-------------------------------------------------------------------------
  19. public class Hand : MonoBehaviour
  20. {
  21. // The flags used to determine how an object is attached to the hand.
  22. [Flags]
  23. public enum AttachmentFlags
  24. {
  25. SnapOnAttach = 1 << 0, // The object should snap to the position of the specified attachment point on the hand.
  26. DetachOthers = 1 << 1, // Other objects attached to this hand will be detached.
  27. DetachFromOtherHand = 1 << 2, // This object will be detached from the other hand.
  28. ParentToHand = 1 << 3, // The object will be parented to the hand.
  29. VelocityMovement = 1 << 4, // The object will attempt to move to match the position and rotation of the hand.
  30. TurnOnKinematic = 1 << 5, // The object will not respond to external physics.
  31. TurnOffGravity = 1 << 6, // The object will not respond to external physics.
  32. AllowSidegrade = 1 << 7, // The object is able to switch from a pinch grab to a grip grab. Decreases likelyhood of a good throw but also decreases likelyhood of accidental drop
  33. };
  34. public const AttachmentFlags defaultAttachmentFlags = AttachmentFlags.ParentToHand |
  35. AttachmentFlags.DetachOthers |
  36. AttachmentFlags.DetachFromOtherHand |
  37. AttachmentFlags.TurnOnKinematic |
  38. AttachmentFlags.SnapOnAttach;
  39. public Hand otherHand;
  40. public SteamVR_Input_Sources handType;
  41. public SteamVR_Behaviour_Pose trackedObject;
  42. public SteamVR_Action_Boolean grabPinchAction = SteamVR_Input.GetAction<SteamVR_Action_Boolean>("GrabPinch");
  43. public SteamVR_Action_Boolean grabGripAction = SteamVR_Input.GetAction<SteamVR_Action_Boolean>("GrabGrip");
  44. public SteamVR_Action_Vibration hapticAction = SteamVR_Input.GetAction<SteamVR_Action_Vibration>("Haptic");
  45. public SteamVR_Action_Boolean uiInteractAction = SteamVR_Input.GetAction<SteamVR_Action_Boolean>("InteractUI");
  46. public bool useHoverSphere = true;
  47. public Transform hoverSphereTransform;
  48. public float hoverSphereRadius = 0.05f;
  49. public LayerMask hoverLayerMask = -1;
  50. public float hoverUpdateInterval = 0.1f;
  51. public bool useControllerHoverComponent = true;
  52. public string controllerHoverComponent = "tip";
  53. public float controllerHoverRadius = 0.075f;
  54. public bool useFingerJointHover = true;
  55. public SteamVR_Skeleton_JointIndexEnum fingerJointHover = SteamVR_Skeleton_JointIndexEnum.indexTip;
  56. public float fingerJointHoverRadius = 0.025f;
  57. [Tooltip("A transform on the hand to center attached objects on")]
  58. public Transform objectAttachmentPoint;
  59. public Camera noSteamVRFallbackCamera;
  60. public float noSteamVRFallbackMaxDistanceNoItem = 10.0f;
  61. public float noSteamVRFallbackMaxDistanceWithItem = 0.5f;
  62. private float noSteamVRFallbackInteractorDistance = -1.0f;
  63. public GameObject renderModelPrefab;
  64. [HideInInspector]
  65. public List<RenderModel> renderModels = new List<RenderModel>();
  66. [HideInInspector]
  67. public RenderModel mainRenderModel;
  68. [HideInInspector]
  69. public RenderModel hoverhighlightRenderModel;
  70. public bool showDebugText = false;
  71. public bool spewDebugText = false;
  72. public bool showDebugInteractables = false;
  73. public struct AttachedObject
  74. {
  75. public GameObject attachedObject;
  76. public Interactable interactable;
  77. public Rigidbody attachedRigidbody;
  78. public CollisionDetectionMode collisionDetectionMode;
  79. public bool attachedRigidbodyWasKinematic;
  80. public bool attachedRigidbodyUsedGravity;
  81. public GameObject originalParent;
  82. public bool isParentedToHand;
  83. public GrabTypes grabbedWithType;
  84. public AttachmentFlags attachmentFlags;
  85. public Vector3 initialPositionalOffset;
  86. public Quaternion initialRotationalOffset;
  87. public Transform attachedOffsetTransform;
  88. public Transform handAttachmentPointTransform;
  89. public Vector3 easeSourcePosition;
  90. public Quaternion easeSourceRotation;
  91. public float attachTime;
  92. public AllowTeleportWhileAttachedToHand allowTeleportWhileAttachedToHand;
  93. public bool HasAttachFlag(AttachmentFlags flag)
  94. {
  95. return (attachmentFlags & flag) == flag;
  96. }
  97. }
  98. private List<AttachedObject> attachedObjects = new List<AttachedObject>();
  99. public ReadOnlyCollection<AttachedObject> AttachedObjects
  100. {
  101. get { return attachedObjects.AsReadOnly(); }
  102. }
  103. public bool hoverLocked { get; private set; }
  104. private Interactable _hoveringInteractable;
  105. private TextMesh debugText;
  106. private int prevOverlappingColliders = 0;
  107. private const int ColliderArraySize = 32;
  108. private Collider[] overlappingColliders;
  109. private Player playerInstance;
  110. private GameObject applicationLostFocusObject;
  111. private SteamVR_Events.Action inputFocusAction;
  112. public bool isActive
  113. {
  114. get
  115. {
  116. if (trackedObject != null)
  117. return trackedObject.isActive;
  118. return this.gameObject.activeInHierarchy;
  119. }
  120. }
  121. public bool isPoseValid
  122. {
  123. get
  124. {
  125. return trackedObject.isValid;
  126. }
  127. }
  128. //-------------------------------------------------
  129. // The Interactable object this Hand is currently hovering over
  130. //-------------------------------------------------
  131. public Interactable hoveringInteractable
  132. {
  133. get { return _hoveringInteractable; }
  134. set
  135. {
  136. if (_hoveringInteractable != value)
  137. {
  138. if (_hoveringInteractable != null)
  139. {
  140. if (spewDebugText)
  141. HandDebugLog("HoverEnd " + _hoveringInteractable.gameObject);
  142. _hoveringInteractable.SendMessage("OnHandHoverEnd", this, SendMessageOptions.DontRequireReceiver);
  143. //Note: The _hoveringInteractable can change after sending the OnHandHoverEnd message so we need to check it again before broadcasting this message
  144. if (_hoveringInteractable != null)
  145. {
  146. this.BroadcastMessage("OnParentHandHoverEnd", _hoveringInteractable, SendMessageOptions.DontRequireReceiver); // let objects attached to the hand know that a hover has ended
  147. }
  148. }
  149. _hoveringInteractable = value;
  150. if (_hoveringInteractable != null)
  151. {
  152. if (spewDebugText)
  153. HandDebugLog("HoverBegin " + _hoveringInteractable.gameObject);
  154. _hoveringInteractable.SendMessage("OnHandHoverBegin", this, SendMessageOptions.DontRequireReceiver);
  155. //Note: The _hoveringInteractable can change after sending the OnHandHoverBegin message so we need to check it again before broadcasting this message
  156. if (_hoveringInteractable != null)
  157. {
  158. this.BroadcastMessage("OnParentHandHoverBegin", _hoveringInteractable, SendMessageOptions.DontRequireReceiver); // let objects attached to the hand know that a hover has begun
  159. }
  160. }
  161. }
  162. }
  163. }
  164. //-------------------------------------------------
  165. // Active GameObject attached to this Hand
  166. //-------------------------------------------------
  167. public GameObject currentAttachedObject
  168. {
  169. get
  170. {
  171. CleanUpAttachedObjectStack();
  172. if (attachedObjects.Count > 0)
  173. {
  174. return attachedObjects[attachedObjects.Count - 1].attachedObject;
  175. }
  176. return null;
  177. }
  178. }
  179. public AttachedObject? currentAttachedObjectInfo
  180. {
  181. get
  182. {
  183. CleanUpAttachedObjectStack();
  184. if (attachedObjects.Count > 0)
  185. {
  186. return attachedObjects[attachedObjects.Count - 1];
  187. }
  188. return null;
  189. }
  190. }
  191. public AllowTeleportWhileAttachedToHand currentAttachedTeleportManager
  192. {
  193. get
  194. {
  195. if (currentAttachedObjectInfo.HasValue)
  196. return currentAttachedObjectInfo.Value.allowTeleportWhileAttachedToHand;
  197. return null;
  198. }
  199. }
  200. public SteamVR_Behaviour_Skeleton skeleton
  201. {
  202. get
  203. {
  204. if (mainRenderModel != null)
  205. return mainRenderModel.GetSkeleton();
  206. return null;
  207. }
  208. }
  209. public void ShowController(bool permanent = false)
  210. {
  211. if (mainRenderModel != null)
  212. mainRenderModel.SetControllerVisibility(true, permanent);
  213. if (hoverhighlightRenderModel != null)
  214. hoverhighlightRenderModel.SetControllerVisibility(true, permanent);
  215. }
  216. public void HideController(bool permanent = false)
  217. {
  218. if (mainRenderModel != null)
  219. mainRenderModel.SetControllerVisibility(false, permanent);
  220. if (hoverhighlightRenderModel != null)
  221. hoverhighlightRenderModel.SetControllerVisibility(false, permanent);
  222. }
  223. public void ShowSkeleton(bool permanent = false)
  224. {
  225. if (mainRenderModel != null)
  226. mainRenderModel.SetHandVisibility(true, permanent);
  227. if (hoverhighlightRenderModel != null)
  228. hoverhighlightRenderModel.SetHandVisibility(true, permanent);
  229. }
  230. public void HideSkeleton(bool permanent = false)
  231. {
  232. if (mainRenderModel != null)
  233. mainRenderModel.SetHandVisibility(false, permanent);
  234. if (hoverhighlightRenderModel != null)
  235. hoverhighlightRenderModel.SetHandVisibility(false, permanent);
  236. }
  237. public bool HasSkeleton()
  238. {
  239. return mainRenderModel != null && mainRenderModel.GetSkeleton() != null;
  240. }
  241. public void Show()
  242. {
  243. SetVisibility(true);
  244. }
  245. public void Hide()
  246. {
  247. SetVisibility(false);
  248. }
  249. public void SetVisibility(bool visible)
  250. {
  251. if (mainRenderModel != null)
  252. mainRenderModel.SetVisibility(visible);
  253. }
  254. public void SetSkeletonRangeOfMotion(EVRSkeletalMotionRange newRangeOfMotion, float blendOverSeconds = 0.1f)
  255. {
  256. for (int renderModelIndex = 0; renderModelIndex < renderModels.Count; renderModelIndex++)
  257. {
  258. renderModels[renderModelIndex].SetSkeletonRangeOfMotion(newRangeOfMotion, blendOverSeconds);
  259. }
  260. }
  261. public void SetTemporarySkeletonRangeOfMotion(SkeletalMotionRangeChange temporaryRangeOfMotionChange, float blendOverSeconds = 0.1f)
  262. {
  263. for (int renderModelIndex = 0; renderModelIndex < renderModels.Count; renderModelIndex++)
  264. {
  265. renderModels[renderModelIndex].SetTemporarySkeletonRangeOfMotion(temporaryRangeOfMotionChange, blendOverSeconds);
  266. }
  267. }
  268. public void ResetTemporarySkeletonRangeOfMotion(float blendOverSeconds = 0.1f)
  269. {
  270. for (int renderModelIndex = 0; renderModelIndex < renderModels.Count; renderModelIndex++)
  271. {
  272. renderModels[renderModelIndex].ResetTemporarySkeletonRangeOfMotion(blendOverSeconds);
  273. }
  274. }
  275. public void SetAnimationState(int stateValue)
  276. {
  277. for (int renderModelIndex = 0; renderModelIndex < renderModels.Count; renderModelIndex++)
  278. {
  279. renderModels[renderModelIndex].SetAnimationState(stateValue);
  280. }
  281. }
  282. public void StopAnimation()
  283. {
  284. for (int renderModelIndex = 0; renderModelIndex < renderModels.Count; renderModelIndex++)
  285. {
  286. renderModels[renderModelIndex].StopAnimation();
  287. }
  288. }
  289. //-------------------------------------------------
  290. // Attach a GameObject to this GameObject
  291. //
  292. // objectToAttach - The GameObject to attach
  293. // flags - The flags to use for attaching the object
  294. // attachmentPoint - Name of the GameObject in the hierarchy of this Hand which should act as the attachment point for this GameObject
  295. //-------------------------------------------------
  296. public void AttachObject(GameObject objectToAttach, GrabTypes grabbedWithType, AttachmentFlags flags = defaultAttachmentFlags, Transform attachmentOffset = null)
  297. {
  298. AttachedObject attachedObject = new AttachedObject();
  299. attachedObject.attachmentFlags = flags;
  300. attachedObject.attachedOffsetTransform = attachmentOffset;
  301. attachedObject.attachTime = Time.time;
  302. if (flags == 0)
  303. {
  304. flags = defaultAttachmentFlags;
  305. }
  306. //Make sure top object on stack is non-null
  307. CleanUpAttachedObjectStack();
  308. //Detach the object if it is already attached so that it can get re-attached at the top of the stack
  309. if (ObjectIsAttached(objectToAttach))
  310. DetachObject(objectToAttach);
  311. //Detach from the other hand if requested
  312. if (attachedObject.HasAttachFlag(AttachmentFlags.DetachFromOtherHand))
  313. {
  314. if (otherHand != null)
  315. otherHand.DetachObject(objectToAttach);
  316. }
  317. if (attachedObject.HasAttachFlag(AttachmentFlags.DetachOthers))
  318. {
  319. //Detach all the objects from the stack
  320. while (attachedObjects.Count > 0)
  321. {
  322. DetachObject(attachedObjects[0].attachedObject);
  323. }
  324. }
  325. if (currentAttachedObject)
  326. {
  327. currentAttachedObject.SendMessage("OnHandFocusLost", this, SendMessageOptions.DontRequireReceiver);
  328. }
  329. attachedObject.attachedObject = objectToAttach;
  330. attachedObject.interactable = objectToAttach.GetComponent<Interactable>();
  331. attachedObject.allowTeleportWhileAttachedToHand = objectToAttach.GetComponent<AllowTeleportWhileAttachedToHand>();
  332. attachedObject.handAttachmentPointTransform = this.transform;
  333. if (attachedObject.interactable != null)
  334. {
  335. if (attachedObject.interactable.attachEaseIn)
  336. {
  337. attachedObject.easeSourcePosition = attachedObject.attachedObject.transform.position;
  338. attachedObject.easeSourceRotation = attachedObject.attachedObject.transform.rotation;
  339. attachedObject.interactable.snapAttachEaseInCompleted = false;
  340. }
  341. if (attachedObject.interactable.useHandObjectAttachmentPoint)
  342. attachedObject.handAttachmentPointTransform = objectAttachmentPoint;
  343. if (attachedObject.interactable.hideHandOnAttach)
  344. Hide();
  345. if (attachedObject.interactable.hideSkeletonOnAttach && mainRenderModel != null && mainRenderModel.displayHandByDefault)
  346. HideSkeleton();
  347. if (attachedObject.interactable.hideControllerOnAttach && mainRenderModel != null && mainRenderModel.displayControllerByDefault)
  348. HideController();
  349. if (attachedObject.interactable.handAnimationOnPickup != 0)
  350. SetAnimationState(attachedObject.interactable.handAnimationOnPickup);
  351. if (attachedObject.interactable.setRangeOfMotionOnPickup != SkeletalMotionRangeChange.None)
  352. SetTemporarySkeletonRangeOfMotion(attachedObject.interactable.setRangeOfMotionOnPickup);
  353. }
  354. attachedObject.originalParent = objectToAttach.transform.parent != null ? objectToAttach.transform.parent.gameObject : null;
  355. attachedObject.attachedRigidbody = objectToAttach.GetComponent<Rigidbody>();
  356. if (attachedObject.attachedRigidbody != null)
  357. {
  358. if (attachedObject.interactable.attachedToHand != null) //already attached to another hand
  359. {
  360. //if it was attached to another hand, get the flags from that hand
  361. for (int attachedIndex = 0; attachedIndex < attachedObject.interactable.attachedToHand.attachedObjects.Count; attachedIndex++)
  362. {
  363. AttachedObject attachedObjectInList = attachedObject.interactable.attachedToHand.attachedObjects[attachedIndex];
  364. if (attachedObjectInList.interactable == attachedObject.interactable)
  365. {
  366. attachedObject.attachedRigidbodyWasKinematic = attachedObjectInList.attachedRigidbodyWasKinematic;
  367. attachedObject.attachedRigidbodyUsedGravity = attachedObjectInList.attachedRigidbodyUsedGravity;
  368. attachedObject.originalParent = attachedObjectInList.originalParent;
  369. }
  370. }
  371. }
  372. else
  373. {
  374. attachedObject.attachedRigidbodyWasKinematic = attachedObject.attachedRigidbody.isKinematic;
  375. attachedObject.attachedRigidbodyUsedGravity = attachedObject.attachedRigidbody.useGravity;
  376. }
  377. }
  378. attachedObject.grabbedWithType = grabbedWithType;
  379. if (attachedObject.HasAttachFlag(AttachmentFlags.ParentToHand))
  380. {
  381. //Parent the object to the hand
  382. objectToAttach.transform.parent = this.transform;
  383. attachedObject.isParentedToHand = true;
  384. }
  385. else
  386. {
  387. attachedObject.isParentedToHand = false;
  388. }
  389. if (attachedObject.HasAttachFlag(AttachmentFlags.SnapOnAttach))
  390. {
  391. if (attachedObject.interactable != null && attachedObject.interactable.skeletonPoser != null && HasSkeleton())
  392. {
  393. SteamVR_Skeleton_PoseSnapshot pose = attachedObject.interactable.skeletonPoser.GetBlendedPose(skeleton);
  394. //snap the object to the center of the attach point
  395. objectToAttach.transform.position = this.transform.TransformPoint(pose.position);
  396. objectToAttach.transform.rotation = this.transform.rotation * pose.rotation;
  397. attachedObject.initialPositionalOffset = attachedObject.handAttachmentPointTransform.InverseTransformPoint(objectToAttach.transform.position);
  398. attachedObject.initialRotationalOffset = Quaternion.Inverse(attachedObject.handAttachmentPointTransform.rotation) * objectToAttach.transform.rotation;
  399. }
  400. else
  401. {
  402. if (attachmentOffset != null)
  403. {
  404. //offset the object from the hand by the positional and rotational difference between the offset transform and the attached object
  405. Quaternion rotDiff = Quaternion.Inverse(attachmentOffset.transform.rotation) * objectToAttach.transform.rotation;
  406. objectToAttach.transform.rotation = attachedObject.handAttachmentPointTransform.rotation * rotDiff;
  407. Vector3 posDiff = objectToAttach.transform.position - attachmentOffset.transform.position;
  408. objectToAttach.transform.position = attachedObject.handAttachmentPointTransform.position + posDiff;
  409. }
  410. else
  411. {
  412. //snap the object to the center of the attach point
  413. objectToAttach.transform.rotation = attachedObject.handAttachmentPointTransform.rotation;
  414. objectToAttach.transform.position = attachedObject.handAttachmentPointTransform.position;
  415. }
  416. Transform followPoint = objectToAttach.transform;
  417. attachedObject.initialPositionalOffset = attachedObject.handAttachmentPointTransform.InverseTransformPoint(followPoint.position);
  418. attachedObject.initialRotationalOffset = Quaternion.Inverse(attachedObject.handAttachmentPointTransform.rotation) * followPoint.rotation;
  419. }
  420. }
  421. else
  422. {
  423. if (attachedObject.interactable != null && attachedObject.interactable.skeletonPoser != null && HasSkeleton())
  424. {
  425. attachedObject.initialPositionalOffset = attachedObject.handAttachmentPointTransform.InverseTransformPoint(objectToAttach.transform.position);
  426. attachedObject.initialRotationalOffset = Quaternion.Inverse(attachedObject.handAttachmentPointTransform.rotation) * objectToAttach.transform.rotation;
  427. }
  428. else
  429. {
  430. if (attachmentOffset != null)
  431. {
  432. //get the initial positional and rotational offsets between the hand and the offset transform
  433. Quaternion rotDiff = Quaternion.Inverse(attachmentOffset.transform.rotation) * objectToAttach.transform.rotation;
  434. Quaternion targetRotation = attachedObject.handAttachmentPointTransform.rotation * rotDiff;
  435. Quaternion rotationPositionBy = targetRotation * Quaternion.Inverse(objectToAttach.transform.rotation);
  436. Vector3 posDiff = (rotationPositionBy * objectToAttach.transform.position) - (rotationPositionBy * attachmentOffset.transform.position);
  437. attachedObject.initialPositionalOffset = attachedObject.handAttachmentPointTransform.InverseTransformPoint(attachedObject.handAttachmentPointTransform.position + posDiff);
  438. attachedObject.initialRotationalOffset = Quaternion.Inverse(attachedObject.handAttachmentPointTransform.rotation) * (attachedObject.handAttachmentPointTransform.rotation * rotDiff);
  439. }
  440. else
  441. {
  442. attachedObject.initialPositionalOffset = attachedObject.handAttachmentPointTransform.InverseTransformPoint(objectToAttach.transform.position);
  443. attachedObject.initialRotationalOffset = Quaternion.Inverse(attachedObject.handAttachmentPointTransform.rotation) * objectToAttach.transform.rotation;
  444. }
  445. }
  446. }
  447. if (attachedObject.HasAttachFlag(AttachmentFlags.TurnOnKinematic))
  448. {
  449. if (attachedObject.attachedRigidbody != null)
  450. {
  451. attachedObject.collisionDetectionMode = attachedObject.attachedRigidbody.collisionDetectionMode;
  452. if (attachedObject.collisionDetectionMode == CollisionDetectionMode.Continuous)
  453. attachedObject.attachedRigidbody.collisionDetectionMode = CollisionDetectionMode.Discrete;
  454. attachedObject.attachedRigidbody.isKinematic = true;
  455. }
  456. }
  457. if (attachedObject.HasAttachFlag(AttachmentFlags.TurnOffGravity))
  458. {
  459. if (attachedObject.attachedRigidbody != null)
  460. {
  461. attachedObject.attachedRigidbody.useGravity = false;
  462. }
  463. }
  464. if (attachedObject.interactable != null && attachedObject.interactable.attachEaseIn)
  465. {
  466. attachedObject.attachedObject.transform.position = attachedObject.easeSourcePosition;
  467. attachedObject.attachedObject.transform.rotation = attachedObject.easeSourceRotation;
  468. }
  469. attachedObjects.Add(attachedObject);
  470. UpdateHovering();
  471. if (spewDebugText)
  472. HandDebugLog("AttachObject " + objectToAttach);
  473. objectToAttach.SendMessage("OnAttachedToHand", this, SendMessageOptions.DontRequireReceiver);
  474. }
  475. public bool ObjectIsAttached(GameObject go)
  476. {
  477. for (int attachedIndex = 0; attachedIndex < attachedObjects.Count; attachedIndex++)
  478. {
  479. if (attachedObjects[attachedIndex].attachedObject == go)
  480. return true;
  481. }
  482. return false;
  483. }
  484. public void ForceHoverUnlock()
  485. {
  486. hoverLocked = false;
  487. }
  488. //-------------------------------------------------
  489. // Detach this GameObject from the attached object stack of this Hand
  490. //
  491. // objectToDetach - The GameObject to detach from this Hand
  492. //-------------------------------------------------
  493. public void DetachObject(GameObject objectToDetach, bool restoreOriginalParent = true)
  494. {
  495. int index = attachedObjects.FindIndex(l => l.attachedObject == objectToDetach);
  496. if (index != -1)
  497. {
  498. if (spewDebugText)
  499. HandDebugLog("DetachObject " + objectToDetach);
  500. GameObject prevTopObject = currentAttachedObject;
  501. if (attachedObjects[index].interactable != null)
  502. {
  503. if (attachedObjects[index].interactable.hideHandOnAttach)
  504. Show();
  505. if (attachedObjects[index].interactable.hideSkeletonOnAttach && mainRenderModel != null && mainRenderModel.displayHandByDefault)
  506. ShowSkeleton();
  507. if (attachedObjects[index].interactable.hideControllerOnAttach && mainRenderModel != null && mainRenderModel.displayControllerByDefault)
  508. ShowController();
  509. if (attachedObjects[index].interactable.handAnimationOnPickup != 0)
  510. StopAnimation();
  511. if (attachedObjects[index].interactable.setRangeOfMotionOnPickup != SkeletalMotionRangeChange.None)
  512. ResetTemporarySkeletonRangeOfMotion();
  513. }
  514. Transform parentTransform = null;
  515. if (attachedObjects[index].isParentedToHand)
  516. {
  517. if (restoreOriginalParent && (attachedObjects[index].originalParent != null))
  518. {
  519. parentTransform = attachedObjects[index].originalParent.transform;
  520. }
  521. if (attachedObjects[index].attachedObject != null)
  522. {
  523. attachedObjects[index].attachedObject.transform.parent = parentTransform;
  524. }
  525. }
  526. if (attachedObjects[index].HasAttachFlag(AttachmentFlags.TurnOnKinematic))
  527. {
  528. if (attachedObjects[index].attachedRigidbody != null)
  529. {
  530. attachedObjects[index].attachedRigidbody.isKinematic = attachedObjects[index].attachedRigidbodyWasKinematic;
  531. attachedObjects[index].attachedRigidbody.collisionDetectionMode = attachedObjects[index].collisionDetectionMode;
  532. }
  533. }
  534. if (attachedObjects[index].HasAttachFlag(AttachmentFlags.TurnOffGravity))
  535. {
  536. if (attachedObjects[index].attachedObject != null)
  537. {
  538. if (attachedObjects[index].attachedRigidbody != null)
  539. attachedObjects[index].attachedRigidbody.useGravity = attachedObjects[index].attachedRigidbodyUsedGravity;
  540. }
  541. }
  542. if (attachedObjects[index].interactable != null && attachedObjects[index].interactable.handFollowTransform && HasSkeleton())
  543. {
  544. skeleton.transform.localPosition = Vector3.zero;
  545. skeleton.transform.localRotation = Quaternion.identity;
  546. }
  547. if (attachedObjects[index].attachedObject != null)
  548. {
  549. if (attachedObjects[index].interactable == null || (attachedObjects[index].interactable != null && attachedObjects[index].interactable.isDestroying == false))
  550. attachedObjects[index].attachedObject.SetActive(true);
  551. attachedObjects[index].attachedObject.SendMessage("OnDetachedFromHand", this, SendMessageOptions.DontRequireReceiver);
  552. }
  553. attachedObjects.RemoveAt(index);
  554. CleanUpAttachedObjectStack();
  555. GameObject newTopObject = currentAttachedObject;
  556. hoverLocked = false;
  557. //Give focus to the top most object on the stack if it changed
  558. if (newTopObject != null && newTopObject != prevTopObject)
  559. {
  560. newTopObject.SetActive(true);
  561. newTopObject.SendMessage("OnHandFocusAcquired", this, SendMessageOptions.DontRequireReceiver);
  562. }
  563. }
  564. CleanUpAttachedObjectStack();
  565. if (mainRenderModel != null)
  566. mainRenderModel.MatchHandToTransform(mainRenderModel.transform);
  567. if (hoverhighlightRenderModel != null)
  568. hoverhighlightRenderModel.MatchHandToTransform(hoverhighlightRenderModel.transform);
  569. }
  570. //-------------------------------------------------
  571. // Get the world velocity of the VR Hand.
  572. //-------------------------------------------------
  573. public Vector3 GetTrackedObjectVelocity(float timeOffset = 0)
  574. {
  575. if (trackedObject == null)
  576. {
  577. Vector3 velocityTarget, angularTarget;
  578. GetUpdatedAttachedVelocities(currentAttachedObjectInfo.Value, out velocityTarget, out angularTarget);
  579. return velocityTarget;
  580. }
  581. if (isActive)
  582. {
  583. if (timeOffset == 0)
  584. return Player.instance.trackingOriginTransform.TransformVector(trackedObject.GetVelocity());
  585. else
  586. {
  587. Vector3 velocity;
  588. Vector3 angularVelocity;
  589. trackedObject.GetVelocitiesAtTimeOffset(timeOffset, out velocity, out angularVelocity);
  590. return Player.instance.trackingOriginTransform.TransformVector(velocity);
  591. }
  592. }
  593. return Vector3.zero;
  594. }
  595. //-------------------------------------------------
  596. // Get the world space angular velocity of the VR Hand.
  597. //-------------------------------------------------
  598. public Vector3 GetTrackedObjectAngularVelocity(float timeOffset = 0)
  599. {
  600. if (trackedObject == null)
  601. {
  602. Vector3 velocityTarget, angularTarget;
  603. GetUpdatedAttachedVelocities(currentAttachedObjectInfo.Value, out velocityTarget, out angularTarget);
  604. return angularTarget;
  605. }
  606. if (isActive)
  607. {
  608. if (timeOffset == 0)
  609. return Player.instance.trackingOriginTransform.TransformDirection(trackedObject.GetAngularVelocity());
  610. else
  611. {
  612. Vector3 velocity;
  613. Vector3 angularVelocity;
  614. trackedObject.GetVelocitiesAtTimeOffset(timeOffset, out velocity, out angularVelocity);
  615. return Player.instance.trackingOriginTransform.TransformDirection(angularVelocity);
  616. }
  617. }
  618. return Vector3.zero;
  619. }
  620. public void GetEstimatedPeakVelocities(out Vector3 velocity, out Vector3 angularVelocity)
  621. {
  622. trackedObject.GetEstimatedPeakVelocities(out velocity, out angularVelocity);
  623. velocity = Player.instance.trackingOriginTransform.TransformVector(velocity);
  624. angularVelocity = Player.instance.trackingOriginTransform.TransformDirection(angularVelocity);
  625. }
  626. //-------------------------------------------------
  627. private void CleanUpAttachedObjectStack()
  628. {
  629. attachedObjects.RemoveAll(l => l.attachedObject == null);
  630. }
  631. //-------------------------------------------------
  632. protected virtual void Awake()
  633. {
  634. inputFocusAction = SteamVR_Events.InputFocusAction(OnInputFocus);
  635. if (hoverSphereTransform == null)
  636. hoverSphereTransform = this.transform;
  637. if (objectAttachmentPoint == null)
  638. objectAttachmentPoint = this.transform;
  639. applicationLostFocusObject = new GameObject("_application_lost_focus");
  640. applicationLostFocusObject.transform.parent = transform;
  641. applicationLostFocusObject.SetActive(false);
  642. if (trackedObject == null)
  643. {
  644. trackedObject = this.gameObject.GetComponent<SteamVR_Behaviour_Pose>();
  645. if (trackedObject != null)
  646. trackedObject.onTransformUpdatedEvent += OnTransformUpdated;
  647. }
  648. }
  649. protected virtual void OnDestroy()
  650. {
  651. if (trackedObject != null)
  652. {
  653. trackedObject.onTransformUpdatedEvent -= OnTransformUpdated;
  654. }
  655. }
  656. protected virtual void OnTransformUpdated(SteamVR_Behaviour_Pose updatedPose, SteamVR_Input_Sources updatedSource)
  657. {
  658. HandFollowUpdate();
  659. }
  660. //-------------------------------------------------
  661. protected virtual IEnumerator Start()
  662. {
  663. // save off player instance
  664. playerInstance = Player.instance;
  665. if (!playerInstance)
  666. {
  667. Debug.LogError("<b>[SteamVR Interaction]</b> No player instance found in Hand Start()", this);
  668. }
  669. if (this.gameObject.layer == 0)
  670. Debug.LogWarning("<b>[SteamVR Interaction]</b> Hand is on default layer. This puts unnecessary strain on hover checks as it is always true for hand colliders (which are then ignored).", this);
  671. else
  672. hoverLayerMask &= ~(1 << this.gameObject.layer); //ignore self for hovering
  673. // allocate array for colliders
  674. overlappingColliders = new Collider[ColliderArraySize];
  675. // We are a "no SteamVR fallback hand" if we have this camera set
  676. // we'll use the right mouse to look around and left mouse to interact
  677. // - don't need to find the device
  678. if (noSteamVRFallbackCamera)
  679. {
  680. yield break;
  681. }
  682. //Debug.Log( "<b>[SteamVR Interaction]</b> Hand - initializing connection routine" );
  683. while (true)
  684. {
  685. if (isPoseValid)
  686. {
  687. InitController();
  688. break;
  689. }
  690. yield return null;
  691. }
  692. }
  693. //-------------------------------------------------
  694. protected virtual void UpdateHovering()
  695. {
  696. if ((noSteamVRFallbackCamera == null) && (isActive == false))
  697. {
  698. return;
  699. }
  700. if (hoverLocked)
  701. return;
  702. if (applicationLostFocusObject.activeSelf)
  703. return;
  704. float closestDistance = float.MaxValue;
  705. Interactable closestInteractable = null;
  706. if (useHoverSphere)
  707. {
  708. float scaledHoverRadius = hoverSphereRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(hoverSphereTransform));
  709. CheckHoveringForTransform(hoverSphereTransform.position, scaledHoverRadius, ref closestDistance, ref closestInteractable, Color.green);
  710. }
  711. if (useControllerHoverComponent && mainRenderModel != null && mainRenderModel.IsControllerVisibile())
  712. {
  713. float scaledHoverRadius = controllerHoverRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(this.transform));
  714. CheckHoveringForTransform(mainRenderModel.GetControllerPosition(controllerHoverComponent), scaledHoverRadius / 2f, ref closestDistance, ref closestInteractable, Color.blue);
  715. }
  716. if (useFingerJointHover && mainRenderModel != null && mainRenderModel.IsHandVisibile())
  717. {
  718. float scaledHoverRadius = fingerJointHoverRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(this.transform));
  719. CheckHoveringForTransform(mainRenderModel.GetBonePosition((int)fingerJointHover), scaledHoverRadius / 2f, ref closestDistance, ref closestInteractable, Color.yellow);
  720. }
  721. // Hover on this one
  722. hoveringInteractable = closestInteractable;
  723. }
  724. protected virtual bool CheckHoveringForTransform(Vector3 hoverPosition, float hoverRadius, ref float closestDistance, ref Interactable closestInteractable, Color debugColor)
  725. {
  726. bool foundCloser = false;
  727. // null out old vals
  728. for (int i = 0; i < overlappingColliders.Length; ++i)
  729. {
  730. overlappingColliders[i] = null;
  731. }
  732. int numColliding = Physics.OverlapSphereNonAlloc(hoverPosition, hoverRadius, overlappingColliders, hoverLayerMask.value);
  733. if (numColliding >= ColliderArraySize)
  734. Debug.LogWarning("<b>[SteamVR Interaction]</b> This hand is overlapping the max number of colliders: " + ColliderArraySize + ". Some collisions may be missed. Increase ColliderArraySize on Hand.cs");
  735. // DebugVar
  736. int iActualColliderCount = 0;
  737. // Pick the closest hovering
  738. for (int colliderIndex = 0; colliderIndex < overlappingColliders.Length; colliderIndex++)
  739. {
  740. Collider collider = overlappingColliders[colliderIndex];
  741. if (collider == null)
  742. continue;
  743. Interactable contacting = collider.GetComponentInParent<Interactable>();
  744. // Yeah, it's null, skip
  745. if (contacting == null)
  746. continue;
  747. // Ignore this collider for hovering
  748. IgnoreHovering ignore = collider.GetComponent<IgnoreHovering>();
  749. if (ignore != null)
  750. {
  751. if (ignore.onlyIgnoreHand == null || ignore.onlyIgnoreHand == this)
  752. {
  753. continue;
  754. }
  755. }
  756. // Can't hover over the object if it's attached
  757. bool hoveringOverAttached = false;
  758. for (int attachedIndex = 0; attachedIndex < attachedObjects.Count; attachedIndex++)
  759. {
  760. if (attachedObjects[attachedIndex].attachedObject == contacting.gameObject)
  761. {
  762. hoveringOverAttached = true;
  763. break;
  764. }
  765. }
  766. if (hoveringOverAttached)
  767. continue;
  768. // Best candidate so far...
  769. float distance = Vector3.Distance(contacting.transform.position, hoverPosition);
  770. //float distance = Vector3.Distance(collider.bounds.center, hoverPosition);
  771. bool lowerPriority = false;
  772. if (closestInteractable != null)
  773. { // compare to closest interactable to check priority
  774. lowerPriority = contacting.hoverPriority < closestInteractable.hoverPriority;
  775. }
  776. bool isCloser = (distance < closestDistance);
  777. if (isCloser && !lowerPriority)
  778. {
  779. closestDistance = distance;
  780. closestInteractable = contacting;
  781. foundCloser = true;
  782. }
  783. iActualColliderCount++;
  784. }
  785. if (showDebugInteractables && foundCloser)
  786. {
  787. Debug.DrawLine(hoverPosition, closestInteractable.transform.position, debugColor, .05f, false);
  788. }
  789. if (iActualColliderCount > 0 && iActualColliderCount != prevOverlappingColliders)
  790. {
  791. prevOverlappingColliders = iActualColliderCount;
  792. if (spewDebugText)
  793. HandDebugLog("Found " + iActualColliderCount + " overlapping colliders.");
  794. }
  795. return foundCloser;
  796. }
  797. //-------------------------------------------------
  798. protected virtual void UpdateNoSteamVRFallback()
  799. {
  800. if (noSteamVRFallbackCamera)
  801. {
  802. Ray ray = noSteamVRFallbackCamera.ScreenPointToRay(Input.mousePosition);
  803. if (attachedObjects.Count > 0)
  804. {
  805. // Holding down the mouse:
  806. // move around a fixed distance from the camera
  807. transform.position = ray.origin + noSteamVRFallbackInteractorDistance * ray.direction;
  808. }
  809. else
  810. {
  811. // Not holding down the mouse:
  812. // cast out a ray to see what we should mouse over
  813. // Don't want to hit the hand and anything underneath it
  814. // So move it back behind the camera when we do the raycast
  815. Vector3 oldPosition = transform.position;
  816. transform.position = noSteamVRFallbackCamera.transform.forward * (-1000.0f);
  817. RaycastHit raycastHit;
  818. if (Physics.Raycast(ray, out raycastHit, noSteamVRFallbackMaxDistanceNoItem))
  819. {
  820. transform.position = raycastHit.point;
  821. // Remember this distance in case we click and drag the mouse
  822. noSteamVRFallbackInteractorDistance = Mathf.Min(noSteamVRFallbackMaxDistanceNoItem, raycastHit.distance);
  823. }
  824. else if (noSteamVRFallbackInteractorDistance > 0.0f)
  825. {
  826. // Move it around at the distance we last had a hit
  827. transform.position = ray.origin + Mathf.Min(noSteamVRFallbackMaxDistanceNoItem, noSteamVRFallbackInteractorDistance) * ray.direction;
  828. }
  829. else
  830. {
  831. // Didn't hit, just leave it where it was
  832. transform.position = oldPosition;
  833. }
  834. }
  835. }
  836. }
  837. //-------------------------------------------------
  838. private void UpdateDebugText()
  839. {
  840. if (showDebugText)
  841. {
  842. if (debugText == null)
  843. {
  844. debugText = new GameObject("_debug_text").AddComponent<TextMesh>();
  845. debugText.fontSize = 120;
  846. debugText.characterSize = 0.001f;
  847. debugText.transform.parent = transform;
  848. debugText.transform.localRotation = Quaternion.Euler(90.0f, 0.0f, 0.0f);
  849. }
  850. if (handType == SteamVR_Input_Sources.RightHand)
  851. {
  852. debugText.transform.localPosition = new Vector3(-0.05f, 0.0f, 0.0f);
  853. debugText.alignment = TextAlignment.Right;
  854. debugText.anchor = TextAnchor.UpperRight;
  855. }
  856. else
  857. {
  858. debugText.transform.localPosition = new Vector3(0.05f, 0.0f, 0.0f);
  859. debugText.alignment = TextAlignment.Left;
  860. debugText.anchor = TextAnchor.UpperLeft;
  861. }
  862. debugText.text = string.Format(
  863. "Hovering: {0}\n" +
  864. "Hover Lock: {1}\n" +
  865. "Attached: {2}\n" +
  866. "Total Attached: {3}\n" +
  867. "Type: {4}\n",
  868. (hoveringInteractable ? hoveringInteractable.gameObject.name : "null"),
  869. hoverLocked,
  870. (currentAttachedObject ? currentAttachedObject.name : "null"),
  871. attachedObjects.Count,
  872. handType.ToString());
  873. }
  874. else
  875. {
  876. if (debugText != null)
  877. {
  878. Destroy(debugText.gameObject);
  879. }
  880. }
  881. }
  882. //-------------------------------------------------
  883. protected virtual void OnEnable()
  884. {
  885. inputFocusAction.enabled = true;
  886. // Stagger updates between hands
  887. float hoverUpdateBegin = ((otherHand != null) && (otherHand.GetInstanceID() < GetInstanceID())) ? (0.5f * hoverUpdateInterval) : (0.0f);
  888. InvokeRepeating("UpdateHovering", hoverUpdateBegin, hoverUpdateInterval);
  889. InvokeRepeating("UpdateDebugText", hoverUpdateBegin, hoverUpdateInterval);
  890. }
  891. //-------------------------------------------------
  892. protected virtual void OnDisable()
  893. {
  894. inputFocusAction.enabled = false;
  895. CancelInvoke();
  896. }
  897. //-------------------------------------------------
  898. protected virtual void Update()
  899. {
  900. UpdateNoSteamVRFallback();
  901. GameObject attachedObject = currentAttachedObject;
  902. if (attachedObject != null)
  903. {
  904. attachedObject.SendMessage("HandAttachedUpdate", this, SendMessageOptions.DontRequireReceiver);
  905. }
  906. if (hoveringInteractable)
  907. {
  908. hoveringInteractable.SendMessage("HandHoverUpdate", this, SendMessageOptions.DontRequireReceiver);
  909. }
  910. }
  911. /// <summary>
  912. /// Returns true when the hand is currently hovering over the interactable passed in
  913. /// </summary>
  914. public bool IsStillHovering(Interactable interactable)
  915. {
  916. return hoveringInteractable == interactable;
  917. }
  918. protected virtual void HandFollowUpdate()
  919. {
  920. GameObject attachedObject = currentAttachedObject;
  921. if (attachedObject != null)
  922. {
  923. if (currentAttachedObjectInfo.Value.interactable != null)
  924. {
  925. SteamVR_Skeleton_PoseSnapshot pose = null;
  926. if (currentAttachedObjectInfo.Value.interactable.skeletonPoser != null && HasSkeleton())
  927. {
  928. pose = currentAttachedObjectInfo.Value.interactable.skeletonPoser.GetBlendedPose(skeleton);
  929. }
  930. if (currentAttachedObjectInfo.Value.interactable.handFollowTransform)
  931. {
  932. Quaternion targetHandRotation;
  933. Vector3 targetHandPosition;
  934. if (pose == null)
  935. {
  936. Quaternion offset = Quaternion.Inverse(this.transform.rotation) * currentAttachedObjectInfo.Value.handAttachmentPointTransform.rotation;
  937. targetHandRotation = currentAttachedObjectInfo.Value.interactable.transform.rotation * Quaternion.Inverse(offset);
  938. Vector3 worldOffset = (this.transform.position - currentAttachedObjectInfo.Value.handAttachmentPointTransform.position);
  939. Quaternion rotationDiff = mainRenderModel.GetHandRotation() * Quaternion.Inverse(this.transform.rotation);
  940. Vector3 localOffset = rotationDiff * worldOffset;
  941. targetHandPosition = currentAttachedObjectInfo.Value.interactable.transform.position + localOffset;
  942. }
  943. else
  944. {
  945. Transform objectT = currentAttachedObjectInfo.Value.attachedObject.transform;
  946. Vector3 oldItemPos = objectT.position;
  947. Quaternion oldItemRot = objectT.transform.rotation;
  948. objectT.position = TargetItemPosition(currentAttachedObjectInfo.Value);
  949. objectT.rotation = TargetItemRotation(currentAttachedObjectInfo.Value);
  950. Vector3 localSkelePos = objectT.InverseTransformPoint(transform.position);
  951. Quaternion localSkeleRot = Quaternion.Inverse(objectT.rotation) * transform.rotation;
  952. objectT.position = oldItemPos;
  953. objectT.rotation = oldItemRot;
  954. targetHandPosition = objectT.TransformPoint(localSkelePos);
  955. targetHandRotation = objectT.rotation * localSkeleRot;
  956. }
  957. if (mainRenderModel != null)
  958. mainRenderModel.SetHandRotation(targetHandRotation);
  959. if (hoverhighlightRenderModel != null)
  960. hoverhighlightRenderModel.SetHandRotation(targetHandRotation);
  961. if (mainRenderModel != null)
  962. mainRenderModel.SetHandPosition(targetHandPosition);
  963. if (hoverhighlightRenderModel != null)
  964. hoverhighlightRenderModel.SetHandPosition(targetHandPosition);
  965. }
  966. }
  967. }
  968. }
  969. protected virtual void FixedUpdate()
  970. {
  971. if (currentAttachedObject != null)
  972. {
  973. AttachedObject attachedInfo = currentAttachedObjectInfo.Value;
  974. if (attachedInfo.attachedObject != null)
  975. {
  976. if (attachedInfo.HasAttachFlag(AttachmentFlags.VelocityMovement))
  977. {
  978. if (attachedInfo.interactable.attachEaseIn == false || attachedInfo.interactable.snapAttachEaseInCompleted)
  979. UpdateAttachedVelocity(attachedInfo);
  980. /*if (attachedInfo.interactable.handFollowTransformPosition)
  981. {
  982. skeleton.transform.position = TargetSkeletonPosition(attachedInfo);
  983. skeleton.transform.rotation = attachedInfo.attachedObject.transform.rotation * attachedInfo.skeletonLockRotation;
  984. }*/
  985. }
  986. else
  987. {
  988. if (attachedInfo.HasAttachFlag(AttachmentFlags.ParentToHand))
  989. {
  990. attachedInfo.attachedObject.transform.position = TargetItemPosition(attachedInfo);
  991. attachedInfo.attachedObject.transform.rotation = TargetItemRotation(attachedInfo);
  992. }
  993. }
  994. if (attachedInfo.interactable.attachEaseIn)
  995. {
  996. float t = Util.RemapNumberClamped(Time.time, attachedInfo.attachTime, attachedInfo.attachTime + attachedInfo.interactable.snapAttachEaseInTime, 0.0f, 1.0f);
  997. if (t < 1.0f)
  998. {
  999. if (attachedInfo.HasAttachFlag(AttachmentFlags.VelocityMovement))
  1000. {
  1001. attachedInfo.attachedRigidbody.velocity = Vector3.zero;
  1002. attachedInfo.attachedRigidbody.angularVelocity = Vector3.zero;
  1003. }
  1004. t = attachedInfo.interactable.snapAttachEaseInCurve.Evaluate(t);
  1005. attachedInfo.attachedObject.transform.position = Vector3.Lerp(attachedInfo.easeSourcePosition, TargetItemPosition(attachedInfo), t);
  1006. attachedInfo.attachedObject.transform.rotation = Quaternion.Lerp(attachedInfo.easeSourceRotation, TargetItemRotation(attachedInfo), t);
  1007. }
  1008. else if (!attachedInfo.interactable.snapAttachEaseInCompleted)
  1009. {
  1010. attachedInfo.interactable.gameObject.SendMessage("OnThrowableAttachEaseInCompleted", this, SendMessageOptions.DontRequireReceiver);
  1011. attachedInfo.interactable.snapAttachEaseInCompleted = true;
  1012. }
  1013. }
  1014. }
  1015. }
  1016. }
  1017. protected const float MaxVelocityChange = 10f;
  1018. protected const float VelocityMagic = 6000f;
  1019. protected const float AngularVelocityMagic = 50f;
  1020. protected const float MaxAngularVelocityChange = 20f;
  1021. protected void UpdateAttachedVelocity(AttachedObject attachedObjectInfo)
  1022. {
  1023. Vector3 velocityTarget, angularTarget;
  1024. bool success = GetUpdatedAttachedVelocities(attachedObjectInfo, out velocityTarget, out angularTarget);
  1025. if (success)
  1026. {
  1027. float scale = SteamVR_Utils.GetLossyScale(currentAttachedObjectInfo.Value.handAttachmentPointTransform);
  1028. float maxAngularVelocityChange = MaxAngularVelocityChange * scale;
  1029. float maxVelocityChange = MaxVelocityChange * scale;
  1030. attachedObjectInfo.attachedRigidbody.velocity = Vector3.MoveTowards(attachedObjectInfo.attachedRigidbody.velocity, velocityTarget, maxVelocityChange);
  1031. attachedObjectInfo.attachedRigidbody.angularVelocity = Vector3.MoveTowards(attachedObjectInfo.attachedRigidbody.angularVelocity, angularTarget, maxAngularVelocityChange);
  1032. }
  1033. }
  1034. /// <summary>
  1035. /// Snap an attached object to its target position and rotation. Good for error correction.
  1036. /// </summary>
  1037. public void ResetAttachedTransform(AttachedObject attachedObject)
  1038. {
  1039. attachedObject.attachedObject.transform.position = TargetItemPosition(attachedObject);
  1040. attachedObject.attachedObject.transform.rotation = TargetItemRotation(attachedObject);
  1041. }
  1042. protected Vector3 TargetItemPosition(AttachedObject attachedObject)
  1043. {
  1044. if (attachedObject.interactable != null && attachedObject.interactable.skeletonPoser != null && HasSkeleton())
  1045. {
  1046. Vector3 tp = attachedObject.handAttachmentPointTransform.InverseTransformPoint(transform.TransformPoint(attachedObject.interactable.skeletonPoser.GetBlendedPose(skeleton).position));
  1047. //tp.x *= -1;
  1048. return currentAttachedObjectInfo.Value.handAttachmentPointTransform.TransformPoint(tp);
  1049. }
  1050. else
  1051. {
  1052. return currentAttachedObjectInfo.Value.handAttachmentPointTransform.TransformPoint(attachedObject.initialPositionalOffset);
  1053. }
  1054. }
  1055. protected Quaternion TargetItemRotation(AttachedObject attachedObject)
  1056. {
  1057. if (attachedObject.interactable != null && attachedObject.interactable.skeletonPoser != null && HasSkeleton())
  1058. {
  1059. Quaternion tr = Quaternion.Inverse(attachedObject.handAttachmentPointTransform.rotation) * (transform.rotation * attachedObject.interactable.skeletonPoser.GetBlendedPose(skeleton).rotation);
  1060. return currentAttachedObjectInfo.Value.handAttachmentPointTransform.rotation * tr;
  1061. }
  1062. else
  1063. {
  1064. return currentAttachedObjectInfo.Value.handAttachmentPointTransform.rotation * attachedObject.initialRotationalOffset;
  1065. }
  1066. }
  1067. protected bool GetUpdatedAttachedVelocities(AttachedObject attachedObjectInfo, out Vector3 velocityTarget, out Vector3 angularTarget)
  1068. {
  1069. bool realNumbers = false;
  1070. float velocityMagic = VelocityMagic;
  1071. float angularVelocityMagic = AngularVelocityMagic;
  1072. Vector3 targetItemPosition = TargetItemPosition(attachedObjectInfo);
  1073. Vector3 positionDelta = (targetItemPosition - attachedObjectInfo.attachedRigidbody.position);
  1074. velocityTarget = (positionDelta * velocityMagic * Time.deltaTime);
  1075. if (float.IsNaN(velocityTarget.x) == false && float.IsInfinity(velocityTarget.x) == false)
  1076. {
  1077. if (noSteamVRFallbackCamera)
  1078. velocityTarget /= 10; //hacky fix for fallback
  1079. realNumbers = true;
  1080. }
  1081. else
  1082. velocityTarget = Vector3.zero;
  1083. Quaternion targetItemRotation = TargetItemRotation(attachedObjectInfo);
  1084. Quaternion rotationDelta = targetItemRotation * Quaternion.Inverse(attachedObjectInfo.attachedObject.transform.rotation);
  1085. float angle;
  1086. Vector3 axis;
  1087. rotationDelta.ToAngleAxis(out angle, out axis);
  1088. if (angle > 180)
  1089. angle -= 360;
  1090. if (angle != 0 && float.IsNaN(axis.x) == false && float.IsInfinity(axis.x) == false)
  1091. {
  1092. angularTarget = angle * axis * angularVelocityMagic * Time.deltaTime;
  1093. if (noSteamVRFallbackCamera)
  1094. angularTarget /= 10; //hacky fix for fallback
  1095. realNumbers &= true;
  1096. }
  1097. else
  1098. angularTarget = Vector3.zero;
  1099. return realNumbers;
  1100. }
  1101. //-------------------------------------------------
  1102. protected virtual void OnInputFocus(bool hasFocus)
  1103. {
  1104. if (hasFocus)
  1105. {
  1106. DetachObject(applicationLostFocusObject, true);
  1107. applicationLostFocusObject.SetActive(false);
  1108. UpdateHovering();
  1109. BroadcastMessage("OnParentHandInputFocusAcquired", SendMessageOptions.DontRequireReceiver);
  1110. }
  1111. else
  1112. {
  1113. applicationLostFocusObject.SetActive(true);
  1114. AttachObject(applicationLostFocusObject, GrabTypes.Scripted, AttachmentFlags.ParentToHand);
  1115. BroadcastMessage("OnParentHandInputFocusLost", SendMessageOptions.DontRequireReceiver);
  1116. }
  1117. }
  1118. //-------------------------------------------------
  1119. protected virtual void OnDrawGizmos()
  1120. {
  1121. if (useHoverSphere && hoverSphereTransform != null)
  1122. {
  1123. Gizmos.color = Color.green;
  1124. float scaledHoverRadius = hoverSphereRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(hoverSphereTransform));
  1125. Gizmos.DrawWireSphere(hoverSphereTransform.position, scaledHoverRadius / 2);
  1126. }
  1127. if (useControllerHoverComponent && mainRenderModel != null && mainRenderModel.IsControllerVisibile())
  1128. {
  1129. Gizmos.color = Color.blue;
  1130. float scaledHoverRadius = controllerHoverRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(this.transform));
  1131. Gizmos.DrawWireSphere(mainRenderModel.GetControllerPosition(controllerHoverComponent), scaledHoverRadius / 2);
  1132. }
  1133. if (useFingerJointHover && mainRenderModel != null && mainRenderModel.IsHandVisibile())
  1134. {
  1135. Gizmos.color = Color.yellow;
  1136. float scaledHoverRadius = fingerJointHoverRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(this.transform));
  1137. Gizmos.DrawWireSphere(mainRenderModel.GetBonePosition((int)fingerJointHover), scaledHoverRadius / 2);
  1138. }
  1139. }
  1140. //-------------------------------------------------
  1141. private void HandDebugLog(string msg)
  1142. {
  1143. if (spewDebugText)
  1144. {
  1145. Debug.Log("<b>[SteamVR Interaction]</b> Hand (" + this.name + "): " + msg);
  1146. }
  1147. }
  1148. //-------------------------------------------------
  1149. // Continue to hover over this object indefinitely, whether or not the Hand moves out of its interaction trigger volume.
  1150. //
  1151. // interactable - The Interactable to hover over indefinitely.
  1152. //-------------------------------------------------
  1153. public void HoverLock(Interactable interactable)
  1154. {
  1155. if (spewDebugText)
  1156. HandDebugLog("HoverLock " + interactable);
  1157. hoverLocked = true;
  1158. hoveringInteractable = interactable;
  1159. }
  1160. //-------------------------------------------------
  1161. // Stop hovering over this object indefinitely.
  1162. //
  1163. // interactable - The hover-locked Interactable to stop hovering over indefinitely.
  1164. //-------------------------------------------------
  1165. public void HoverUnlock(Interactable interactable)
  1166. {
  1167. if (spewDebugText)
  1168. HandDebugLog("HoverUnlock " + interactable);
  1169. if (hoveringInteractable == interactable)
  1170. {
  1171. hoverLocked = false;
  1172. }
  1173. }
  1174. public void TriggerHapticPulse(ushort microSecondsDuration)
  1175. {
  1176. float seconds = (float)microSecondsDuration / 1000000f;
  1177. hapticAction.Execute(0, seconds, 1f / seconds, 1, handType);
  1178. }
  1179. public void TriggerHapticPulse(float duration, float frequency, float amplitude)
  1180. {
  1181. hapticAction.Execute(0, duration, frequency, amplitude, handType);
  1182. }
  1183. public void ShowGrabHint()
  1184. {
  1185. ControllerButtonHints.ShowButtonHint(this, grabGripAction); //todo: assess
  1186. }
  1187. public void HideGrabHint()
  1188. {
  1189. ControllerButtonHints.HideButtonHint(this, grabGripAction); //todo: assess
  1190. }
  1191. public void ShowGrabHint(string text)
  1192. {
  1193. ControllerButtonHints.ShowTextHint(this, grabGripAction, text);
  1194. }
  1195. public GrabTypes GetGrabStarting(GrabTypes explicitType = GrabTypes.None)
  1196. {
  1197. if (explicitType != GrabTypes.None)
  1198. {
  1199. if (noSteamVRFallbackCamera)
  1200. {
  1201. if (Input.GetMouseButtonDown(0))
  1202. return explicitType;
  1203. else
  1204. return GrabTypes.None;
  1205. }
  1206. if (explicitType == GrabTypes.Pinch && grabPinchAction.GetStateDown(handType))
  1207. return GrabTypes.Pinch;
  1208. if (explicitType == GrabTypes.Grip && grabGripAction.GetStateDown(handType))
  1209. return GrabTypes.Grip;
  1210. }
  1211. else
  1212. {
  1213. if (noSteamVRFallbackCamera)
  1214. {
  1215. if (Input.GetMouseButtonDown(0))
  1216. return GrabTypes.Grip;
  1217. else
  1218. return GrabTypes.None;
  1219. }
  1220. if (grabPinchAction != null && grabPinchAction.GetStateDown(handType))
  1221. return GrabTypes.Pinch;
  1222. if (grabGripAction != null && grabGripAction.GetStateDown(handType))
  1223. return GrabTypes.Grip;
  1224. }
  1225. return GrabTypes.None;
  1226. }
  1227. public GrabTypes GetGrabEnding(GrabTypes explicitType = GrabTypes.None)
  1228. {
  1229. if (explicitType != GrabTypes.None)
  1230. {
  1231. if (noSteamVRFallbackCamera)
  1232. {
  1233. if (Input.GetMouseButtonUp(0))
  1234. return explicitType;
  1235. else
  1236. return GrabTypes.None;
  1237. }
  1238. if (explicitType == GrabTypes.Pinch && grabPinchAction.GetStateUp(handType))
  1239. return GrabTypes.Pinch;
  1240. if (explicitType == GrabTypes.Grip && grabGripAction.GetStateUp(handType))
  1241. return GrabTypes.Grip;
  1242. }
  1243. else
  1244. {
  1245. if (noSteamVRFallbackCamera)
  1246. {
  1247. if (Input.GetMouseButtonUp(0))
  1248. return GrabTypes.Grip;
  1249. else
  1250. return GrabTypes.None;
  1251. }
  1252. if (grabPinchAction.GetStateUp(handType))
  1253. return GrabTypes.Pinch;
  1254. if (grabGripAction.GetStateUp(handType))
  1255. return GrabTypes.Grip;
  1256. }
  1257. return GrabTypes.None;
  1258. }
  1259. public bool IsGrabEnding(GameObject attachedObject)
  1260. {
  1261. for (int attachedObjectIndex = 0; attachedObjectIndex < attachedObjects.Count; attachedObjectIndex++)
  1262. {
  1263. if (attachedObjects[attachedObjectIndex].attachedObject == attachedObject)
  1264. {
  1265. return IsGrabbingWithType(attachedObjects[attachedObjectIndex].grabbedWithType) == false;
  1266. }
  1267. }
  1268. return false;
  1269. }
  1270. public bool IsGrabbingWithType(GrabTypes type)
  1271. {
  1272. if (noSteamVRFallbackCamera)
  1273. {
  1274. if (Input.GetMouseButton(0))
  1275. return true;
  1276. else
  1277. return false;
  1278. }
  1279. switch (type)
  1280. {
  1281. case GrabTypes.Pinch:
  1282. return grabPinchAction.GetState(handType);
  1283. case GrabTypes.Grip:
  1284. return grabGripAction.GetState(handType);
  1285. default:
  1286. return false;
  1287. }
  1288. }
  1289. public bool IsGrabbingWithOppositeType(GrabTypes type)
  1290. {
  1291. if (noSteamVRFallbackCamera)
  1292. {
  1293. if (Input.GetMouseButton(0))
  1294. return true;
  1295. else
  1296. return false;
  1297. }
  1298. switch (type)
  1299. {
  1300. case GrabTypes.Pinch:
  1301. return grabGripAction.GetState(handType);
  1302. case GrabTypes.Grip:
  1303. return grabPinchAction.GetState(handType);
  1304. default:
  1305. return false;
  1306. }
  1307. }
  1308. public GrabTypes GetBestGrabbingType()
  1309. {
  1310. return GetBestGrabbingType(GrabTypes.None);
  1311. }
  1312. public GrabTypes GetBestGrabbingType(GrabTypes preferred, bool forcePreference = false)
  1313. {
  1314. if (noSteamVRFallbackCamera)
  1315. {
  1316. if (Input.GetMouseButton(0))
  1317. return preferred;
  1318. else
  1319. return GrabTypes.None;
  1320. }
  1321. if (preferred == GrabTypes.Pinch)
  1322. {
  1323. if (grabPinchAction.GetState(handType))
  1324. return GrabTypes.Pinch;
  1325. else if (forcePreference)
  1326. return GrabTypes.None;
  1327. }
  1328. if (preferred == GrabTypes.Grip)
  1329. {
  1330. if (grabGripAction.GetState(handType))
  1331. return GrabTypes.Grip;
  1332. else if (forcePreference)
  1333. return GrabTypes.None;
  1334. }
  1335. if (grabPinchAction.GetState(handType))
  1336. return GrabTypes.Pinch;
  1337. if (grabGripAction.GetState(handType))
  1338. return GrabTypes.Grip;
  1339. return GrabTypes.None;
  1340. }
  1341. //-------------------------------------------------
  1342. private void InitController()
  1343. {
  1344. if (spewDebugText)
  1345. HandDebugLog("Hand " + name + " connected with type " + handType.ToString());
  1346. bool hadOldRendermodel = mainRenderModel != null;
  1347. EVRSkeletalMotionRange oldRM_rom = EVRSkeletalMotionRange.WithController;
  1348. if (hadOldRendermodel)
  1349. oldRM_rom = mainRenderModel.GetSkeletonRangeOfMotion;
  1350. foreach (RenderModel r in renderModels)
  1351. {
  1352. if (r != null)
  1353. Destroy(r.gameObject);
  1354. }
  1355. renderModels.Clear();
  1356. GameObject renderModelInstance = GameObject.Instantiate(renderModelPrefab);
  1357. renderModelInstance.layer = gameObject.layer;
  1358. renderModelInstance.tag = gameObject.tag;
  1359. renderModelInstance.transform.parent = this.transform;
  1360. renderModelInstance.transform.localPosition = Vector3.zero;
  1361. renderModelInstance.transform.localRotation = Quaternion.identity;
  1362. renderModelInstance.transform.localScale = renderModelPrefab.transform.localScale;
  1363. //TriggerHapticPulse(800); //pulse on controller init
  1364. int deviceIndex = trackedObject.GetDeviceIndex();
  1365. mainRenderModel = renderModelInstance.GetComponent<RenderModel>();
  1366. renderModels.Add(mainRenderModel);
  1367. if (hadOldRendermodel)
  1368. mainRenderModel.SetSkeletonRangeOfMotion(oldRM_rom);
  1369. this.BroadcastMessage("SetInputSource", handType, SendMessageOptions.DontRequireReceiver); // let child objects know we've initialized
  1370. this.BroadcastMessage("OnHandInitialized", deviceIndex, SendMessageOptions.DontRequireReceiver); // let child objects know we've initialized
  1371. }
  1372. public void SetRenderModel(GameObject prefab)
  1373. {
  1374. renderModelPrefab = prefab;
  1375. if (mainRenderModel != null && isPoseValid)
  1376. InitController();
  1377. }
  1378. public void SetHoverRenderModel(RenderModel hoverRenderModel)
  1379. {
  1380. hoverhighlightRenderModel = hoverRenderModel;
  1381. renderModels.Add(hoverRenderModel);
  1382. }
  1383. public int GetDeviceIndex()
  1384. {
  1385. return trackedObject.GetDeviceIndex();
  1386. }
  1387. }
  1388. [System.Serializable]
  1389. public class HandEvent : UnityEvent<Hand> { }
  1390. }