SteamVR_Behaviour_Skeleton.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. //======= Copyright (c) Valve Corporation, All rights reserved. ===============
  2. using System;
  3. using System.Collections;
  4. using UnityEngine;
  5. using UnityEngine.Events;
  6. using Valve.VR;
  7. namespace Valve.VR
  8. {
  9. public class SteamVR_Behaviour_Skeleton : MonoBehaviour
  10. {
  11. [Tooltip("If not set, will try to auto assign this based on 'Skeleton' + inputSource")]
  12. /// <summary>The action this component will use to update the model. Must be a Skeleton type action.</summary>
  13. public SteamVR_Action_Skeleton skeletonAction;
  14. /// <summary>The device this action should apply to. Any if the action is not device specific.</summary>
  15. [Tooltip("The device this action should apply to. Any if the action is not device specific.")]
  16. public SteamVR_Input_Sources inputSource;
  17. /// <summary>The range of motion you'd like the hand to move in. With controller is the best estimate of the fingers wrapped around a controller. Without is from a flat hand to a fist.</summary>
  18. [Tooltip("The range of motion you'd like the hand to move in. With controller is the best estimate of the fingers wrapped around a controller. Without is from a flat hand to a fist.")]
  19. public EVRSkeletalMotionRange rangeOfMotion = EVRSkeletalMotionRange.WithoutController;
  20. /// <summary>The root Transform of the skeleton. Needs to have a child (wrist) then wrist should have children in the order thumb, index, middle, ring, pinky</summary>
  21. [Tooltip("This needs to be in the order of: root -> wrist -> thumb, index, middle, ring, pinky")]
  22. public Transform skeletonRoot;
  23. /// <summary>The transform this transform should be relative to</summary>
  24. [Tooltip("If not set, relative to parent")]
  25. public Transform origin;
  26. /// <summary>Whether or not to update this transform's position and rotation inline with the skeleton transforms or if this is handled in another script</summary>
  27. [Tooltip("Set to true if you want this script to update its position and rotation. False if this will be handled elsewhere")]
  28. public bool updatePose = true;
  29. /// <summary>Check this to not set the positions of the bones. This is helpful for differently scaled skeletons.</summary>
  30. [Tooltip("Check this to not set the positions of the bones. This is helpful for differently scaled skeletons.")]
  31. public bool onlySetRotations = false;
  32. /// <summary>
  33. /// How much of a blend to apply to the transform positions and rotations.
  34. /// Set to 0 for the transform orientation to be set by an animation.
  35. /// Set to 1 for the transform orientation to be set by the skeleton action.
  36. /// </summary>
  37. [Range(0, 1)]
  38. [Tooltip("Modify this to blend between animations setup on the hand")]
  39. public float skeletonBlend = 1f;
  40. /// <summary>This Unity event will fire whenever the position or rotation of the bones are updated.</summary>
  41. public SteamVR_Behaviour_SkeletonEvent onBoneTransformsUpdated;
  42. /// <summary>This Unity event will fire whenever the position or rotation of this transform is updated.</summary>
  43. public SteamVR_Behaviour_SkeletonEvent onTransformUpdated;
  44. /// <summary>This Unity event will fire whenever the position or rotation of this transform is changed.</summary>
  45. public SteamVR_Behaviour_SkeletonEvent onTransformChanged;
  46. /// <summary>This Unity event will fire whenever the device is connected or disconnected</summary>
  47. public SteamVR_Behaviour_Skeleton_ConnectedChangedEvent onConnectedChanged;
  48. /// <summary>This Unity event will fire whenever the device's tracking state changes</summary>
  49. public SteamVR_Behaviour_Skeleton_TrackingChangedEvent onTrackingChanged;
  50. /// <summary>This C# event will fire whenever the position or rotation of this transform is updated.</summary>
  51. public UpdateHandler onBoneTransformsUpdatedEvent;
  52. /// <summary>This C# event will fire whenever the position or rotation of this transform is updated.</summary>
  53. public UpdateHandler onTransformUpdatedEvent;
  54. /// <summary>This C# event will fire whenever the position or rotation of this transform is changed.</summary>
  55. public ChangeHandler onTransformChangedEvent;
  56. /// <summary>This C# event will fire whenever the device is connected or disconnected</summary>
  57. public DeviceConnectedChangeHandler onConnectedChangedEvent;
  58. /// <summary>This C# event will fire whenever the device's tracking state changes</summary>
  59. public TrackingChangeHandler onTrackingChangedEvent;
  60. protected SteamVR_Skeleton_Poser blendPoser;
  61. protected SteamVR_Skeleton_PoseSnapshot blendSnapshot;
  62. /// <summary>Can be set to mirror the bone data across the x axis</summary>
  63. [Tooltip("Is this rendermodel a mirror of another one?")]
  64. public MirrorType mirroring;
  65. /// <summary>Returns whether this action is bound and the action set is active</summary>
  66. public bool isActive { get { return skeletonAction.GetActive(); } }
  67. /// <summary>An array of five 0-1 values representing how curled a finger is. 0 being straight, 1 being fully curled. Index 0 being thumb, index 4 being pinky</summary>
  68. public float[] fingerCurls { get { return skeletonAction.GetFingerCurls(); } }
  69. /// <summary>An 0-1 value representing how curled a finger is. 0 being straight, 1 being fully curled.</summary>
  70. public float thumbCurl { get { return skeletonAction.GetFingerCurl(SteamVR_Skeleton_FingerIndexEnum.thumb); } }
  71. /// <summary>An 0-1 value representing how curled a finger is. 0 being straight, 1 being fully curled.</summary>
  72. public float indexCurl { get { return skeletonAction.GetFingerCurl(SteamVR_Skeleton_FingerIndexEnum.index); } }
  73. /// <summary>An 0-1 value representing how curled a finger is. 0 being straight, 1 being fully curled.</summary>
  74. public float middleCurl { get { return skeletonAction.GetFingerCurl(SteamVR_Skeleton_FingerIndexEnum.middle); } }
  75. /// <summary>An 0-1 value representing how curled a finger is. 0 being straight, 1 being fully curled.</summary>
  76. public float ringCurl { get { return skeletonAction.GetFingerCurl(SteamVR_Skeleton_FingerIndexEnum.ring); } }
  77. /// <summary>An 0-1 value representing how curled a finger is. 0 being straight, 1 being fully curled.</summary>
  78. public float pinkyCurl { get { return skeletonAction.GetFingerCurl(SteamVR_Skeleton_FingerIndexEnum.pinky); } }
  79. public Transform root { get { return bones[SteamVR_Skeleton_JointIndexes.root]; } }
  80. public Transform wrist { get { return bones[SteamVR_Skeleton_JointIndexes.wrist]; } }
  81. public Transform indexMetacarpal { get { return bones[SteamVR_Skeleton_JointIndexes.indexMetacarpal]; } }
  82. public Transform indexProximal { get { return bones[SteamVR_Skeleton_JointIndexes.indexProximal]; } }
  83. public Transform indexMiddle { get { return bones[SteamVR_Skeleton_JointIndexes.indexMiddle]; } }
  84. public Transform indexDistal { get { return bones[SteamVR_Skeleton_JointIndexes.indexDistal]; } }
  85. public Transform indexTip { get { return bones[SteamVR_Skeleton_JointIndexes.indexTip]; } }
  86. public Transform middleMetacarpal { get { return bones[SteamVR_Skeleton_JointIndexes.middleMetacarpal]; } }
  87. public Transform middleProximal { get { return bones[SteamVR_Skeleton_JointIndexes.middleProximal]; } }
  88. public Transform middleMiddle { get { return bones[SteamVR_Skeleton_JointIndexes.middleMiddle]; } }
  89. public Transform middleDistal { get { return bones[SteamVR_Skeleton_JointIndexes.middleDistal]; } }
  90. public Transform middleTip { get { return bones[SteamVR_Skeleton_JointIndexes.middleTip]; } }
  91. public Transform pinkyMetacarpal { get { return bones[SteamVR_Skeleton_JointIndexes.pinkyMetacarpal]; } }
  92. public Transform pinkyProximal { get { return bones[SteamVR_Skeleton_JointIndexes.pinkyProximal]; } }
  93. public Transform pinkyMiddle { get { return bones[SteamVR_Skeleton_JointIndexes.pinkyMiddle]; } }
  94. public Transform pinkyDistal { get { return bones[SteamVR_Skeleton_JointIndexes.pinkyDistal]; } }
  95. public Transform pinkyTip { get { return bones[SteamVR_Skeleton_JointIndexes.pinkyTip]; } }
  96. public Transform ringMetacarpal { get { return bones[SteamVR_Skeleton_JointIndexes.ringMetacarpal]; } }
  97. public Transform ringProximal { get { return bones[SteamVR_Skeleton_JointIndexes.ringProximal]; } }
  98. public Transform ringMiddle { get { return bones[SteamVR_Skeleton_JointIndexes.ringMiddle]; } }
  99. public Transform ringDistal { get { return bones[SteamVR_Skeleton_JointIndexes.ringDistal]; } }
  100. public Transform ringTip { get { return bones[SteamVR_Skeleton_JointIndexes.ringTip]; } }
  101. public Transform thumbMetacarpal { get { return bones[SteamVR_Skeleton_JointIndexes.thumbMetacarpal]; } } //doesn't exist - mapped to proximal
  102. public Transform thumbProximal { get { return bones[SteamVR_Skeleton_JointIndexes.thumbProximal]; } }
  103. public Transform thumbMiddle { get { return bones[SteamVR_Skeleton_JointIndexes.thumbMiddle]; } }
  104. public Transform thumbDistal { get { return bones[SteamVR_Skeleton_JointIndexes.thumbDistal]; } }
  105. public Transform thumbTip { get { return bones[SteamVR_Skeleton_JointIndexes.thumbTip]; } }
  106. public Transform thumbAux { get { return bones[SteamVR_Skeleton_JointIndexes.thumbAux]; } }
  107. public Transform indexAux { get { return bones[SteamVR_Skeleton_JointIndexes.indexAux]; } }
  108. public Transform middleAux { get { return bones[SteamVR_Skeleton_JointIndexes.middleAux]; } }
  109. public Transform ringAux { get { return bones[SteamVR_Skeleton_JointIndexes.ringAux]; } }
  110. public Transform pinkyAux { get { return bones[SteamVR_Skeleton_JointIndexes.pinkyAux]; } }
  111. /// <summary>An array of all the finger proximal joint transforms</summary>
  112. public Transform[] proximals { get; protected set; }
  113. /// <summary>An array of all the finger middle joint transforms</summary>
  114. public Transform[] middles { get; protected set; }
  115. /// <summary>An array of all the finger distal joint transforms</summary>
  116. public Transform[] distals { get; protected set; }
  117. /// <summary>An array of all the finger tip transforms</summary>
  118. public Transform[] tips { get; protected set; }
  119. /// <summary>An array of all the finger aux transforms</summary>
  120. public Transform[] auxs { get; protected set; }
  121. protected Coroutine blendRoutine;
  122. protected Coroutine rangeOfMotionBlendRoutine;
  123. protected Coroutine attachRoutine;
  124. protected Transform[] bones;
  125. /// <summary>The range of motion that is set temporarily (call ResetTemporaryRangeOfMotion to reset to rangeOfMotion)</summary>
  126. protected EVRSkeletalMotionRange? temporaryRangeOfMotion = null;
  127. /// <summary>
  128. /// Get the accuracy level of the skeletal tracking data.
  129. /// <para/>* Estimated: Body part location can’t be directly determined by the device. Any skeletal pose provided by the device is estimated based on the active buttons, triggers, joysticks, or other input sensors. Examples include the Vive Controller and gamepads.
  130. /// <para/>* Partial: Body part location can be measured directly but with fewer degrees of freedom than the actual body part.Certain body part positions may be unmeasured by the device and estimated from other input data.Examples include Knuckles or gloves that only measure finger curl
  131. /// <para/>* Full: Body part location can be measured directly throughout the entire range of motion of the body part.Examples include hi-end mocap systems, or gloves that measure the rotation of each finger segment.
  132. /// </summary>
  133. public EVRSkeletalTrackingLevel skeletalTrackingLevel
  134. {
  135. get { return skeletonAction.skeletalTrackingLevel; }
  136. }
  137. /// <summary>Returns true if we are in the process of blending the skeletonBlend field (between animation and bone data)</summary>
  138. public bool isBlending
  139. {
  140. get
  141. {
  142. return blendRoutine != null;
  143. }
  144. }
  145. public float predictedSecondsFromNow
  146. {
  147. get
  148. {
  149. return skeletonAction.predictedSecondsFromNow;
  150. }
  151. set
  152. {
  153. skeletonAction.predictedSecondsFromNow = value;
  154. }
  155. }
  156. public SteamVR_ActionSet actionSet
  157. {
  158. get
  159. {
  160. return skeletonAction.actionSet;
  161. }
  162. }
  163. public SteamVR_ActionDirections direction
  164. {
  165. get
  166. {
  167. return skeletonAction.direction;
  168. }
  169. }
  170. protected virtual void Awake()
  171. {
  172. AssignBonesArray();
  173. proximals = new Transform[] { thumbProximal, indexProximal, middleProximal, ringProximal, pinkyProximal };
  174. middles = new Transform[] { thumbMiddle, indexMiddle, middleMiddle, ringMiddle, pinkyMiddle };
  175. distals = new Transform[] { thumbDistal, indexDistal, middleDistal, ringDistal, pinkyDistal };
  176. tips = new Transform[] { thumbTip, indexTip, middleTip, ringTip, pinkyTip };
  177. auxs = new Transform[] { thumbAux, indexAux, middleAux, ringAux, pinkyAux };
  178. CheckSkeletonAction();
  179. }
  180. protected virtual void CheckSkeletonAction()
  181. {
  182. if (skeletonAction == null)
  183. skeletonAction = SteamVR_Input.GetAction<SteamVR_Action_Skeleton>("Skeleton" + inputSource.ToString());
  184. }
  185. protected virtual void AssignBonesArray()
  186. {
  187. bones = skeletonRoot.GetComponentsInChildren<Transform>();
  188. }
  189. protected virtual void OnEnable()
  190. {
  191. CheckSkeletonAction();
  192. SteamVR_Input.onSkeletonsUpdated += SteamVR_Input_OnSkeletonsUpdated;
  193. if (skeletonAction != null)
  194. {
  195. skeletonAction.onDeviceConnectedChanged += OnDeviceConnectedChanged;
  196. skeletonAction.onTrackingChanged += OnTrackingChanged;
  197. }
  198. }
  199. protected virtual void OnDisable()
  200. {
  201. SteamVR_Input.onSkeletonsUpdated -= SteamVR_Input_OnSkeletonsUpdated;
  202. if (skeletonAction != null)
  203. {
  204. skeletonAction.onDeviceConnectedChanged -= OnDeviceConnectedChanged;
  205. skeletonAction.onTrackingChanged -= OnTrackingChanged;
  206. }
  207. }
  208. private void OnDeviceConnectedChanged(SteamVR_Action_Skeleton fromAction, bool deviceConnected)
  209. {
  210. if (onConnectedChanged != null)
  211. onConnectedChanged.Invoke(this, inputSource, deviceConnected);
  212. if (onConnectedChangedEvent != null)
  213. onConnectedChangedEvent.Invoke(this, inputSource, deviceConnected);
  214. }
  215. private void OnTrackingChanged(SteamVR_Action_Skeleton fromAction, ETrackingResult trackingState)
  216. {
  217. if (onTrackingChanged != null)
  218. onTrackingChanged.Invoke(this, inputSource, trackingState);
  219. if (onTrackingChangedEvent != null)
  220. onTrackingChangedEvent.Invoke(this, inputSource, trackingState);
  221. }
  222. protected virtual void SteamVR_Input_OnSkeletonsUpdated(bool skipSendingEvents)
  223. {
  224. UpdateSkeleton();
  225. }
  226. protected virtual void UpdateSkeleton()
  227. {
  228. if (skeletonAction == null || skeletonAction.active == false)
  229. return;
  230. if (updatePose)
  231. UpdatePose();
  232. if (blendPoser != null && skeletonBlend < 1)
  233. {
  234. blendSnapshot = blendPoser.GetBlendedPose(this);
  235. }
  236. if (rangeOfMotionBlendRoutine == null)
  237. {
  238. if (temporaryRangeOfMotion != null)
  239. skeletonAction.SetRangeOfMotion(temporaryRangeOfMotion.Value);
  240. else
  241. skeletonAction.SetRangeOfMotion(rangeOfMotion); //this may be a frame behind
  242. UpdateSkeletonTransforms();
  243. }
  244. }
  245. /// <summary>
  246. /// Sets a temporary range of motion for this action that can easily be reset (using ResetTemporaryRangeOfMotion).
  247. /// This is useful for short range of motion changes, for example picking up a controller shaped object
  248. /// </summary>
  249. /// <param name="newRangeOfMotion">The new range of motion you want to apply (temporarily)</param>
  250. /// <param name="blendOverSeconds">How long you want the blend to the new range of motion to take (in seconds)</param>
  251. public void SetTemporaryRangeOfMotion(EVRSkeletalMotionRange newRangeOfMotion, float blendOverSeconds = 0.1f)
  252. {
  253. if (rangeOfMotion != newRangeOfMotion || temporaryRangeOfMotion != newRangeOfMotion)
  254. {
  255. TemporaryRangeOfMotionBlend(newRangeOfMotion, blendOverSeconds);
  256. }
  257. }
  258. /// <summary>
  259. /// Resets the previously set temporary range of motion.
  260. /// Will return to the range of motion defined by the rangeOfMotion field.
  261. /// </summary>
  262. /// <param name="blendOverSeconds">How long you want the blend to the standard range of motion to take (in seconds)</param>
  263. public void ResetTemporaryRangeOfMotion(float blendOverSeconds = 0.1f)
  264. {
  265. ResetTemporaryRangeOfMotionBlend(blendOverSeconds);
  266. }
  267. /// <summary>
  268. /// Permanently sets the range of motion for this component.
  269. /// </summary>
  270. /// <param name="newRangeOfMotion">
  271. /// The new range of motion to be set.
  272. /// WithController being the best estimation of where fingers are wrapped around the controller (pressing buttons, etc).
  273. /// WithoutController being a range between a flat hand and a fist.</param>
  274. /// <param name="blendOverSeconds">How long you want the blend to the new range of motion to take (in seconds)</param>
  275. public void SetRangeOfMotion(EVRSkeletalMotionRange newRangeOfMotion, float blendOverSeconds = 0.1f)
  276. {
  277. if (rangeOfMotion != newRangeOfMotion)
  278. {
  279. RangeOfMotionBlend(newRangeOfMotion, blendOverSeconds);
  280. }
  281. }
  282. /// <summary>
  283. /// Blend from the current skeletonBlend amount to full bone data. (skeletonBlend = 1)
  284. /// </summary>
  285. /// <param name="overTime">How long you want the blend to take (in seconds)</param>
  286. public void BlendToSkeleton(float overTime = 0.1f)
  287. {
  288. BlendTo(1, overTime);
  289. }
  290. /// <summary>
  291. /// Blend from the current skeletonBlend amount to pose animation. (skeletonBlend = 0)
  292. /// Note: This will ignore the root position and rotation of the pose.
  293. /// </summary>
  294. /// <param name="overTime">How long you want the blend to take (in seconds)</param>
  295. public void BlendToPoser(SteamVR_Skeleton_Poser poser, float overTime = 0.1f)
  296. {
  297. if (poser == null)
  298. return;
  299. blendPoser = poser;
  300. BlendTo(0, overTime);
  301. }
  302. /// <summary>
  303. /// Blend from the current skeletonBlend amount to full animation data (no bone data. skeletonBlend = 0)
  304. /// </summary>
  305. /// <param name="overTime">How long you want the blend to take (in seconds)</param>
  306. public void BlendToAnimation(float overTime = 0.1f)
  307. {
  308. BlendTo(0, overTime);
  309. }
  310. /// <summary>
  311. /// Blend from the current skeletonBlend amount to a specified new amount.
  312. /// </summary>
  313. /// <param name="blendToAmount">The amount of blend you want to apply.
  314. /// 0 being fully set by animations, 1 being fully set by bone data from the action.</param>
  315. /// <param name="overTime">How long you want the blend to take (in seconds)</param>
  316. public void BlendTo(float blendToAmount, float overTime)
  317. {
  318. if (blendRoutine != null)
  319. StopCoroutine(blendRoutine);
  320. if (this.gameObject.activeInHierarchy)
  321. blendRoutine = StartCoroutine(DoBlendRoutine(blendToAmount, overTime));
  322. }
  323. protected IEnumerator DoBlendRoutine(float blendToAmount, float overTime)
  324. {
  325. float startTime = Time.time;
  326. float endTime = startTime + overTime;
  327. float startAmount = skeletonBlend;
  328. while (Time.time < endTime)
  329. {
  330. yield return null;
  331. skeletonBlend = Mathf.Lerp(startAmount, blendToAmount, (Time.time - startTime) / overTime);
  332. }
  333. skeletonBlend = blendToAmount;
  334. blendRoutine = null;
  335. }
  336. protected void RangeOfMotionBlend(EVRSkeletalMotionRange newRangeOfMotion, float blendOverSeconds)
  337. {
  338. if (rangeOfMotionBlendRoutine != null)
  339. StopCoroutine(rangeOfMotionBlendRoutine);
  340. EVRSkeletalMotionRange oldRangeOfMotion = rangeOfMotion;
  341. rangeOfMotion = newRangeOfMotion;
  342. if (this.gameObject.activeInHierarchy)
  343. {
  344. rangeOfMotionBlendRoutine = StartCoroutine(DoRangeOfMotionBlend(oldRangeOfMotion, newRangeOfMotion, blendOverSeconds));
  345. }
  346. }
  347. protected void TemporaryRangeOfMotionBlend(EVRSkeletalMotionRange newRangeOfMotion, float blendOverSeconds)
  348. {
  349. if (rangeOfMotionBlendRoutine != null)
  350. StopCoroutine(rangeOfMotionBlendRoutine);
  351. EVRSkeletalMotionRange oldRangeOfMotion = rangeOfMotion;
  352. if (temporaryRangeOfMotion != null)
  353. oldRangeOfMotion = temporaryRangeOfMotion.Value;
  354. temporaryRangeOfMotion = newRangeOfMotion;
  355. if (this.gameObject.activeInHierarchy)
  356. {
  357. rangeOfMotionBlendRoutine = StartCoroutine(DoRangeOfMotionBlend(oldRangeOfMotion, newRangeOfMotion, blendOverSeconds));
  358. }
  359. }
  360. protected void ResetTemporaryRangeOfMotionBlend(float blendOverSeconds)
  361. {
  362. if (temporaryRangeOfMotion != null)
  363. {
  364. if (rangeOfMotionBlendRoutine != null)
  365. StopCoroutine(rangeOfMotionBlendRoutine);
  366. EVRSkeletalMotionRange oldRangeOfMotion = temporaryRangeOfMotion.Value;
  367. EVRSkeletalMotionRange newRangeOfMotion = rangeOfMotion;
  368. temporaryRangeOfMotion = null;
  369. if (this.gameObject.activeInHierarchy)
  370. {
  371. rangeOfMotionBlendRoutine = StartCoroutine(DoRangeOfMotionBlend(oldRangeOfMotion, newRangeOfMotion, blendOverSeconds));
  372. }
  373. }
  374. }
  375. protected IEnumerator DoRangeOfMotionBlend(EVRSkeletalMotionRange oldRangeOfMotion, EVRSkeletalMotionRange newRangeOfMotion, float overTime)
  376. {
  377. float startTime = Time.time;
  378. float endTime = startTime + overTime;
  379. Vector3[] oldBonePositions;
  380. Quaternion[] oldBoneRotations;
  381. Vector3[] newBonePositions;
  382. Quaternion[] newBoneRotations;
  383. while (Time.time < endTime)
  384. {
  385. yield return null;
  386. float lerp = (Time.time - startTime) / overTime;
  387. if (skeletonBlend > 0)
  388. {
  389. skeletonAction.SetRangeOfMotion(oldRangeOfMotion);
  390. skeletonAction.UpdateValueWithoutEvents();
  391. oldBonePositions = (Vector3[])GetBonePositions().Clone();
  392. oldBoneRotations = (Quaternion[])GetBoneRotations().Clone();
  393. skeletonAction.SetRangeOfMotion(newRangeOfMotion);
  394. skeletonAction.UpdateValueWithoutEvents();
  395. newBonePositions = GetBonePositions();
  396. newBoneRotations = GetBoneRotations();
  397. for (int boneIndex = 0; boneIndex < bones.Length; boneIndex++)
  398. {
  399. if (bones[boneIndex] == null)
  400. continue;
  401. if (SteamVR_Utils.IsValid(newBoneRotations[boneIndex]) == false || SteamVR_Utils.IsValid(oldBoneRotations[boneIndex]) == false)
  402. {
  403. continue;
  404. }
  405. Vector3 blendedRangeOfMotionPosition = Vector3.Lerp(oldBonePositions[boneIndex], newBonePositions[boneIndex], lerp);
  406. Quaternion blendedRangeOfMotionRotation = Quaternion.Lerp(oldBoneRotations[boneIndex], newBoneRotations[boneIndex], lerp);
  407. if (skeletonBlend < 1)
  408. {
  409. if (blendPoser != null)
  410. {
  411. SetBonePosition(boneIndex, Vector3.Lerp(blendSnapshot.bonePositions[boneIndex], blendedRangeOfMotionPosition, skeletonBlend));
  412. SetBoneRotation(boneIndex, Quaternion.Lerp(GetBlendPoseForBone(boneIndex, blendedRangeOfMotionRotation), blendedRangeOfMotionRotation, skeletonBlend));
  413. }
  414. else
  415. {
  416. SetBonePosition(boneIndex, Vector3.Lerp(bones[boneIndex].localPosition, blendedRangeOfMotionPosition, skeletonBlend));
  417. SetBoneRotation(boneIndex, Quaternion.Lerp(bones[boneIndex].localRotation, blendedRangeOfMotionRotation, skeletonBlend));
  418. }
  419. }
  420. else
  421. {
  422. SetBonePosition(boneIndex, blendedRangeOfMotionPosition);
  423. SetBoneRotation(boneIndex, blendedRangeOfMotionRotation);
  424. }
  425. }
  426. }
  427. if (onBoneTransformsUpdated != null)
  428. onBoneTransformsUpdated.Invoke(this, inputSource);
  429. if (onBoneTransformsUpdatedEvent != null)
  430. onBoneTransformsUpdatedEvent.Invoke(this, inputSource);
  431. }
  432. rangeOfMotionBlendRoutine = null;
  433. }
  434. protected virtual Quaternion GetBlendPoseForBone(int boneIndex, Quaternion skeletonRotation)
  435. {
  436. Quaternion poseRotation = blendSnapshot.boneRotations[boneIndex];
  437. return poseRotation;
  438. }
  439. protected virtual void UpdateSkeletonTransforms()
  440. {
  441. Vector3[] bonePositions = GetBonePositions();
  442. Quaternion[] boneRotations = GetBoneRotations();
  443. if (skeletonBlend <= 0)
  444. {
  445. if (blendPoser != null)
  446. {
  447. SteamVR_Skeleton_Pose_Hand mainPose = blendPoser.skeletonMainPose.GetHand(inputSource);
  448. for (int boneIndex = 0; boneIndex < bones.Length; boneIndex++)
  449. {
  450. if (bones[boneIndex] == null)
  451. continue;
  452. if ((boneIndex == SteamVR_Skeleton_JointIndexes.wrist && mainPose.ignoreWristPoseData) ||
  453. (boneIndex == SteamVR_Skeleton_JointIndexes.root && mainPose.ignoreRootPoseData))
  454. {
  455. SetBonePosition(boneIndex, bonePositions[boneIndex]);
  456. SetBoneRotation(boneIndex, boneRotations[boneIndex]);
  457. }
  458. else
  459. {
  460. Quaternion poseRotation = GetBlendPoseForBone(boneIndex, boneRotations[boneIndex]);
  461. SetBonePosition(boneIndex, blendSnapshot.bonePositions[boneIndex]);
  462. SetBoneRotation(boneIndex, poseRotation);
  463. }
  464. }
  465. }
  466. }
  467. else if (skeletonBlend >= 1)
  468. {
  469. for (int boneIndex = 0; boneIndex < bones.Length; boneIndex++)
  470. {
  471. if (bones[boneIndex] == null)
  472. continue;
  473. SetBonePosition(boneIndex, bonePositions[boneIndex]);
  474. SetBoneRotation(boneIndex, boneRotations[boneIndex]);
  475. }
  476. }
  477. else
  478. {
  479. for (int boneIndex = 0; boneIndex < bones.Length; boneIndex++)
  480. {
  481. if (bones[boneIndex] == null)
  482. continue;
  483. if (blendPoser != null)
  484. {
  485. SteamVR_Skeleton_Pose_Hand mainPose = blendPoser.skeletonMainPose.GetHand(inputSource);
  486. if ((boneIndex == SteamVR_Skeleton_JointIndexes.wrist && mainPose.ignoreWristPoseData) ||
  487. (boneIndex == SteamVR_Skeleton_JointIndexes.root && mainPose.ignoreRootPoseData))
  488. {
  489. SetBonePosition(boneIndex, bonePositions[boneIndex]);
  490. SetBoneRotation(boneIndex, boneRotations[boneIndex]);
  491. }
  492. else
  493. {
  494. Quaternion poseRotation = GetBlendPoseForBone(boneIndex, boneRotations[boneIndex]);
  495. SetBonePosition(boneIndex, Vector3.Lerp(blendSnapshot.bonePositions[boneIndex], bonePositions[boneIndex], skeletonBlend));
  496. SetBoneRotation(boneIndex, Quaternion.Lerp(poseRotation, boneRotations[boneIndex], skeletonBlend));
  497. }
  498. }
  499. else
  500. {
  501. SetBonePosition(boneIndex, Vector3.Lerp(bones[boneIndex].localPosition, bonePositions[boneIndex], skeletonBlend));
  502. SetBoneRotation(boneIndex, Quaternion.Lerp(bones[boneIndex].localRotation, boneRotations[boneIndex], skeletonBlend));
  503. }
  504. }
  505. }
  506. if (onBoneTransformsUpdated != null)
  507. onBoneTransformsUpdated.Invoke(this, inputSource);
  508. if (onBoneTransformsUpdatedEvent != null)
  509. onBoneTransformsUpdatedEvent.Invoke(this, inputSource);
  510. }
  511. protected virtual void SetBonePosition(int boneIndex, Vector3 localPosition)
  512. {
  513. if (onlySetRotations == false) //ignore position sets if we're only setting rotations
  514. bones[boneIndex].localPosition = localPosition;
  515. }
  516. protected virtual void SetBoneRotation(int boneIndex, Quaternion localRotation)
  517. {
  518. bones[boneIndex].localRotation = localRotation;
  519. }
  520. /// <summary>
  521. /// Gets the transform for a bone by the joint index. Joint indexes specified in: SteamVR_Skeleton_JointIndexes
  522. /// </summary>
  523. /// <param name="joint">The joint index of the bone. Specified in SteamVR_Skeleton_JointIndexes</param>
  524. public virtual Transform GetBone(int joint)
  525. {
  526. if (bones == null || bones.Length == 0)
  527. Awake();
  528. return bones[joint];
  529. }
  530. /// <summary>
  531. /// Gets the position of the transform for a bone by the joint index. Joint indexes specified in: SteamVR_Skeleton_JointIndexes
  532. /// </summary>
  533. /// <param name="joint">The joint index of the bone. Specified in SteamVR_Skeleton_JointIndexes</param>
  534. /// <param name="local">true to get the localspace position for the joint (position relative to this joint's parent)</param>
  535. public Vector3 GetBonePosition(int joint, bool local = false)
  536. {
  537. if (local)
  538. return bones[joint].localPosition;
  539. else
  540. return bones[joint].position;
  541. }
  542. /// <summary>
  543. /// Gets the rotation of the transform for a bone by the joint index. Joint indexes specified in: SteamVR_Skeleton_JointIndexes
  544. /// </summary>
  545. /// <param name="joint">The joint index of the bone. Specified in SteamVR_Skeleton_JointIndexes</param>
  546. /// <param name="local">true to get the localspace rotation for the joint (rotation relative to this joint's parent)</param>
  547. public Quaternion GetBoneRotation(int joint, bool local = false)
  548. {
  549. if (local)
  550. return bones[joint].localRotation;
  551. else
  552. return bones[joint].rotation;
  553. }
  554. protected Vector3[] GetBonePositions()
  555. {
  556. Vector3[] rawSkeleton = skeletonAction.GetBonePositions();
  557. if (mirroring == MirrorType.LeftToRight || mirroring == MirrorType.RightToLeft)
  558. {
  559. for (int boneIndex = 0; boneIndex < rawSkeleton.Length; boneIndex++)
  560. {
  561. if (boneIndex == SteamVR_Skeleton_JointIndexes.wrist || IsMetacarpal(boneIndex))
  562. {
  563. rawSkeleton[boneIndex].Scale(new Vector3(-1, 1, 1));
  564. }
  565. else if (boneIndex != SteamVR_Skeleton_JointIndexes.root)
  566. {
  567. rawSkeleton[boneIndex] = rawSkeleton[boneIndex] * -1;
  568. }
  569. }
  570. }
  571. return rawSkeleton;
  572. }
  573. protected Quaternion rightFlipAngle = Quaternion.AngleAxis(180, Vector3.right);
  574. protected Quaternion[] GetBoneRotations()
  575. {
  576. Quaternion[] rawSkeleton = skeletonAction.GetBoneRotations();
  577. if (mirroring == MirrorType.LeftToRight || mirroring == MirrorType.RightToLeft)
  578. {
  579. for (int boneIndex = 0; boneIndex < rawSkeleton.Length; boneIndex++)
  580. {
  581. if (boneIndex == SteamVR_Skeleton_JointIndexes.wrist)
  582. {
  583. rawSkeleton[boneIndex].y = rawSkeleton[boneIndex].y * -1;
  584. rawSkeleton[boneIndex].z = rawSkeleton[boneIndex].z * -1;
  585. }
  586. if (IsMetacarpal(boneIndex))
  587. {
  588. rawSkeleton[boneIndex] = rightFlipAngle * rawSkeleton[boneIndex];
  589. }
  590. }
  591. }
  592. return rawSkeleton;
  593. }
  594. protected virtual void UpdatePose()
  595. {
  596. if (skeletonAction == null)
  597. return;
  598. Vector3 skeletonPosition = skeletonAction.GetLocalPosition();
  599. Quaternion skeletonRotation = skeletonAction.GetLocalRotation();
  600. if (origin == null)
  601. {
  602. if (this.transform.parent != null)
  603. {
  604. skeletonPosition = this.transform.parent.TransformPoint(skeletonPosition);
  605. skeletonRotation = this.transform.parent.rotation * skeletonRotation;
  606. }
  607. }
  608. else
  609. {
  610. skeletonPosition = origin.TransformPoint(skeletonPosition);
  611. skeletonRotation = origin.rotation * skeletonRotation;
  612. }
  613. if (skeletonAction.poseChanged)
  614. {
  615. if (onTransformChanged != null)
  616. onTransformChanged.Invoke(this, inputSource);
  617. if (onTransformChangedEvent != null)
  618. onTransformChangedEvent.Invoke(this, inputSource);
  619. }
  620. this.transform.position = skeletonPosition;
  621. this.transform.rotation = skeletonRotation;
  622. if (onTransformUpdated != null)
  623. onTransformUpdated.Invoke(this, inputSource);
  624. }
  625. /// <summary>
  626. /// Returns an array of positions/rotations that represent the state of each bone in a reference pose.
  627. /// </summary>
  628. /// <param name="referencePose">Which reference pose to return</param>
  629. public void ForceToReferencePose(EVRSkeletalReferencePose referencePose)
  630. {
  631. bool temporarySession = false;
  632. if (Application.isEditor && Application.isPlaying == false)
  633. {
  634. temporarySession = SteamVR.InitializeTemporarySession(true);
  635. Awake();
  636. #if UNITY_EDITOR
  637. //gotta wait a bit for steamvr input to startup //todo: implement steamvr_input.isready
  638. string title = "SteamVR";
  639. string text = "Getting reference pose...";
  640. float msToWait = 3000;
  641. float increment = 100;
  642. for (float timer = 0; timer < msToWait; timer += increment)
  643. {
  644. bool cancel = UnityEditor.EditorUtility.DisplayCancelableProgressBar(title, text, timer / msToWait);
  645. if (cancel)
  646. {
  647. UnityEditor.EditorUtility.ClearProgressBar();
  648. if (temporarySession)
  649. SteamVR.ExitTemporarySession();
  650. return;
  651. }
  652. System.Threading.Thread.Sleep((int)increment);
  653. }
  654. UnityEditor.EditorUtility.ClearProgressBar();
  655. #endif
  656. skeletonAction.actionSet.Activate();
  657. SteamVR_ActionSet_Manager.UpdateActionStates(true);
  658. skeletonAction.UpdateValueWithoutEvents();
  659. }
  660. if (skeletonAction.active == false)
  661. {
  662. Debug.LogError("<b>[SteamVR Input]</b> Please turn on your " + inputSource.ToString() + " controller and ensure SteamVR is open.");
  663. return;
  664. }
  665. SteamVR_Utils.RigidTransform[] transforms = skeletonAction.GetReferenceTransforms(EVRSkeletalTransformSpace.Parent, referencePose);
  666. if (transforms == null || transforms.Length == 0)
  667. {
  668. Debug.LogError("<b>[SteamVR Input]</b> Unable to get the reference transform for " + inputSource.ToString() + ". Please make sure SteamVR is open and both controllers are connected.");
  669. }
  670. for (int boneIndex = 0; boneIndex < transforms.Length; boneIndex++)
  671. {
  672. bones[boneIndex].localPosition = transforms[boneIndex].pos;
  673. bones[boneIndex].localRotation = transforms[boneIndex].rot;
  674. }
  675. if (temporarySession)
  676. SteamVR.ExitTemporarySession();
  677. }
  678. protected bool IsMetacarpal(int boneIndex)
  679. {
  680. return (boneIndex == SteamVR_Skeleton_JointIndexes.indexMetacarpal ||
  681. boneIndex == SteamVR_Skeleton_JointIndexes.middleMetacarpal ||
  682. boneIndex == SteamVR_Skeleton_JointIndexes.ringMetacarpal ||
  683. boneIndex == SteamVR_Skeleton_JointIndexes.pinkyMetacarpal ||
  684. boneIndex == SteamVR_Skeleton_JointIndexes.thumbMetacarpal);
  685. }
  686. public enum MirrorType
  687. {
  688. None,
  689. LeftToRight,
  690. RightToLeft
  691. }
  692. public delegate void ActiveChangeHandler(SteamVR_Behaviour_Skeleton fromAction, SteamVR_Input_Sources inputSource, bool active);
  693. public delegate void ChangeHandler(SteamVR_Behaviour_Skeleton fromAction, SteamVR_Input_Sources inputSource);
  694. public delegate void UpdateHandler(SteamVR_Behaviour_Skeleton fromAction, SteamVR_Input_Sources inputSource);
  695. public delegate void TrackingChangeHandler(SteamVR_Behaviour_Skeleton fromAction, SteamVR_Input_Sources inputSource, ETrackingResult trackingState);
  696. public delegate void ValidPoseChangeHandler(SteamVR_Behaviour_Skeleton fromAction, SteamVR_Input_Sources inputSource, bool validPose);
  697. public delegate void DeviceConnectedChangeHandler(SteamVR_Behaviour_Skeleton fromAction, SteamVR_Input_Sources inputSource, bool deviceConnected);
  698. }
  699. }