2
0

SteamVR_Behaviour_Skeleton.cs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  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. /// <summary>Can be set to mirror the bone data across the x axis</summary>
  61. [Tooltip("Is this rendermodel a mirror of another one?")]
  62. public MirrorType mirroring;
  63. [Header("No Skeleton - Fallback")]
  64. [Tooltip("The fallback SkeletonPoser to drive hand animation when no skeleton data is available")]
  65. /// <summary>The fallback SkeletonPoser to drive hand animation when no skeleton data is available</summary>
  66. public SteamVR_Skeleton_Poser fallbackPoser;
  67. [Tooltip("The fallback action to drive finger curl values when no skeleton data is available")]
  68. /// <summary>The fallback SkeletonPoser to drive hand animation when no skeleton data is available</summary>
  69. public SteamVR_Action_Single fallbackCurlAction;
  70. /// <summary>
  71. /// Is the skeleton action bound?
  72. /// </summary>
  73. public bool skeletonAvailable { get { return skeletonAction.activeBinding; } }
  74. /// <summary>The current skeletonPoser we're getting pose data from</summary>
  75. protected SteamVR_Skeleton_Poser blendPoser;
  76. /// <summary>The current pose snapshot</summary>
  77. protected SteamVR_Skeleton_PoseSnapshot blendSnapshot = null;
  78. /// <summary>Returns whether this action is bound and the action set is active</summary>
  79. public bool isActive { get { return skeletonAction.GetActive(); } }
  80. /// <summary>An array of five 0-1 values representing how curled a finger is. 0 being straight, 1 being fully curled. 0 being thumb, 4 being pinky</summary>
  81. public float[] fingerCurls
  82. {
  83. get
  84. {
  85. if (skeletonAvailable)
  86. {
  87. return skeletonAction.GetFingerCurls();
  88. }
  89. else
  90. {
  91. //fallback, return array where each finger curl is just the fallback curl action value
  92. float[] curls = new float[5];
  93. for (int i = 0; i < 5; i++)
  94. {
  95. curls[i] = fallbackCurlAction.GetAxis(inputSource);
  96. }
  97. return curls;
  98. }
  99. }
  100. }
  101. /// <summary>An 0-1 value representing how curled a finger is. 0 being straight, 1 being fully curled.</summary>
  102. public float thumbCurl
  103. {
  104. get
  105. {
  106. if (skeletonAvailable)
  107. return skeletonAction.GetFingerCurl(SteamVR_Skeleton_FingerIndexEnum.thumb);
  108. else
  109. return fallbackCurlAction.GetAxis(inputSource);
  110. }
  111. }
  112. /// <summary>An 0-1 value representing how curled a finger is. 0 being straight, 1 being fully curled.</summary>
  113. public float indexCurl
  114. {
  115. get
  116. {
  117. if (skeletonAvailable)
  118. return skeletonAction.GetFingerCurl(SteamVR_Skeleton_FingerIndexEnum.index);
  119. else
  120. return fallbackCurlAction.GetAxis(inputSource);
  121. }
  122. }
  123. /// <summary>An 0-1 value representing how curled a finger is. 0 being straight, 1 being fully curled.</summary>
  124. public float middleCurl
  125. {
  126. get
  127. {
  128. if (skeletonAvailable)
  129. return skeletonAction.GetFingerCurl(SteamVR_Skeleton_FingerIndexEnum.middle);
  130. else
  131. return fallbackCurlAction.GetAxis(inputSource);
  132. }
  133. }
  134. /// <summary>An 0-1 value representing how curled a finger is. 0 being straight, 1 being fully curled.</summary>
  135. public float ringCurl
  136. {
  137. get
  138. {
  139. if (skeletonAvailable)
  140. return skeletonAction.GetFingerCurl(SteamVR_Skeleton_FingerIndexEnum.ring);
  141. else
  142. return fallbackCurlAction.GetAxis(inputSource);
  143. }
  144. }
  145. /// <summary>An 0-1 value representing how curled a finger is. 0 being straight, 1 being fully curled.</summary>
  146. public float pinkyCurl
  147. {
  148. get
  149. {
  150. if (skeletonAvailable)
  151. return skeletonAction.GetFingerCurl(SteamVR_Skeleton_FingerIndexEnum.pinky);
  152. else
  153. return fallbackCurlAction.GetAxis(inputSource);
  154. }
  155. }
  156. public Transform root { get { return bones[SteamVR_Skeleton_JointIndexes.root]; } }
  157. public Transform wrist { get { return bones[SteamVR_Skeleton_JointIndexes.wrist]; } }
  158. public Transform indexMetacarpal { get { return bones[SteamVR_Skeleton_JointIndexes.indexMetacarpal]; } }
  159. public Transform indexProximal { get { return bones[SteamVR_Skeleton_JointIndexes.indexProximal]; } }
  160. public Transform indexMiddle { get { return bones[SteamVR_Skeleton_JointIndexes.indexMiddle]; } }
  161. public Transform indexDistal { get { return bones[SteamVR_Skeleton_JointIndexes.indexDistal]; } }
  162. public Transform indexTip { get { return bones[SteamVR_Skeleton_JointIndexes.indexTip]; } }
  163. public Transform middleMetacarpal { get { return bones[SteamVR_Skeleton_JointIndexes.middleMetacarpal]; } }
  164. public Transform middleProximal { get { return bones[SteamVR_Skeleton_JointIndexes.middleProximal]; } }
  165. public Transform middleMiddle { get { return bones[SteamVR_Skeleton_JointIndexes.middleMiddle]; } }
  166. public Transform middleDistal { get { return bones[SteamVR_Skeleton_JointIndexes.middleDistal]; } }
  167. public Transform middleTip { get { return bones[SteamVR_Skeleton_JointIndexes.middleTip]; } }
  168. public Transform pinkyMetacarpal { get { return bones[SteamVR_Skeleton_JointIndexes.pinkyMetacarpal]; } }
  169. public Transform pinkyProximal { get { return bones[SteamVR_Skeleton_JointIndexes.pinkyProximal]; } }
  170. public Transform pinkyMiddle { get { return bones[SteamVR_Skeleton_JointIndexes.pinkyMiddle]; } }
  171. public Transform pinkyDistal { get { return bones[SteamVR_Skeleton_JointIndexes.pinkyDistal]; } }
  172. public Transform pinkyTip { get { return bones[SteamVR_Skeleton_JointIndexes.pinkyTip]; } }
  173. public Transform ringMetacarpal { get { return bones[SteamVR_Skeleton_JointIndexes.ringMetacarpal]; } }
  174. public Transform ringProximal { get { return bones[SteamVR_Skeleton_JointIndexes.ringProximal]; } }
  175. public Transform ringMiddle { get { return bones[SteamVR_Skeleton_JointIndexes.ringMiddle]; } }
  176. public Transform ringDistal { get { return bones[SteamVR_Skeleton_JointIndexes.ringDistal]; } }
  177. public Transform ringTip { get { return bones[SteamVR_Skeleton_JointIndexes.ringTip]; } }
  178. public Transform thumbMetacarpal { get { return bones[SteamVR_Skeleton_JointIndexes.thumbMetacarpal]; } } //doesn't exist - mapped to proximal
  179. public Transform thumbProximal { get { return bones[SteamVR_Skeleton_JointIndexes.thumbProximal]; } }
  180. public Transform thumbMiddle { get { return bones[SteamVR_Skeleton_JointIndexes.thumbMiddle]; } }
  181. public Transform thumbDistal { get { return bones[SteamVR_Skeleton_JointIndexes.thumbDistal]; } }
  182. public Transform thumbTip { get { return bones[SteamVR_Skeleton_JointIndexes.thumbTip]; } }
  183. public Transform thumbAux { get { return bones[SteamVR_Skeleton_JointIndexes.thumbAux]; } }
  184. public Transform indexAux { get { return bones[SteamVR_Skeleton_JointIndexes.indexAux]; } }
  185. public Transform middleAux { get { return bones[SteamVR_Skeleton_JointIndexes.middleAux]; } }
  186. public Transform ringAux { get { return bones[SteamVR_Skeleton_JointIndexes.ringAux]; } }
  187. public Transform pinkyAux { get { return bones[SteamVR_Skeleton_JointIndexes.pinkyAux]; } }
  188. /// <summary>An array of all the finger proximal joint transforms</summary>
  189. public Transform[] proximals { get; protected set; }
  190. /// <summary>An array of all the finger middle joint transforms</summary>
  191. public Transform[] middles { get; protected set; }
  192. /// <summary>An array of all the finger distal joint transforms</summary>
  193. public Transform[] distals { get; protected set; }
  194. /// <summary>An array of all the finger tip transforms</summary>
  195. public Transform[] tips { get; protected set; }
  196. /// <summary>An array of all the finger aux transforms</summary>
  197. public Transform[] auxs { get; protected set; }
  198. protected Coroutine blendRoutine;
  199. protected Coroutine rangeOfMotionBlendRoutine;
  200. protected Coroutine attachRoutine;
  201. protected Transform[] bones;
  202. /// <summary>The range of motion that is set temporarily (call ResetTemporaryRangeOfMotion to reset to rangeOfMotion)</summary>
  203. protected EVRSkeletalMotionRange? temporaryRangeOfMotion = null;
  204. /// <summary>
  205. /// Get the accuracy level of the skeletal tracking data.
  206. /// <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.
  207. /// <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
  208. /// <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.
  209. /// </summary>
  210. public EVRSkeletalTrackingLevel skeletalTrackingLevel
  211. {
  212. get
  213. {
  214. if (skeletonAvailable)
  215. {
  216. return skeletonAction.skeletalTrackingLevel;
  217. }
  218. else
  219. {
  220. return EVRSkeletalTrackingLevel.VRSkeletalTracking_Estimated;
  221. }
  222. }
  223. }
  224. /// <summary>Returns true if we are in the process of blending the skeletonBlend field (between animation and bone data)</summary>
  225. public bool isBlending
  226. {
  227. get
  228. {
  229. return blendRoutine != null;
  230. }
  231. }
  232. /*
  233. public float predictedSecondsFromNow
  234. {
  235. get
  236. {
  237. return skeletonAction.predictedSecondsFromNow;
  238. }
  239. set
  240. {
  241. skeletonAction.predictedSecondsFromNow = value;
  242. }
  243. }
  244. */
  245. public SteamVR_ActionSet actionSet
  246. {
  247. get
  248. {
  249. return skeletonAction.actionSet;
  250. }
  251. }
  252. public SteamVR_ActionDirections direction
  253. {
  254. get
  255. {
  256. return skeletonAction.direction;
  257. }
  258. }
  259. protected virtual void Awake()
  260. {
  261. SteamVR.Initialize();
  262. AssignBonesArray();
  263. proximals = new Transform[] { thumbProximal, indexProximal, middleProximal, ringProximal, pinkyProximal };
  264. middles = new Transform[] { thumbMiddle, indexMiddle, middleMiddle, ringMiddle, pinkyMiddle };
  265. distals = new Transform[] { thumbDistal, indexDistal, middleDistal, ringDistal, pinkyDistal };
  266. tips = new Transform[] { thumbTip, indexTip, middleTip, ringTip, pinkyTip };
  267. auxs = new Transform[] { thumbAux, indexAux, middleAux, ringAux, pinkyAux };
  268. CheckSkeletonAction();
  269. }
  270. protected virtual void CheckSkeletonAction()
  271. {
  272. if (skeletonAction == null)
  273. skeletonAction = SteamVR_Input.GetAction<SteamVR_Action_Skeleton>("Skeleton" + inputSource.ToString());
  274. }
  275. protected virtual void AssignBonesArray()
  276. {
  277. bones = skeletonRoot.GetComponentsInChildren<Transform>();
  278. }
  279. protected virtual void OnEnable()
  280. {
  281. CheckSkeletonAction();
  282. SteamVR_Input.onSkeletonsUpdated += SteamVR_Input_OnSkeletonsUpdated;
  283. if (skeletonAction != null)
  284. {
  285. skeletonAction.onDeviceConnectedChanged += OnDeviceConnectedChanged;
  286. skeletonAction.onTrackingChanged += OnTrackingChanged;
  287. }
  288. }
  289. protected virtual void OnDisable()
  290. {
  291. SteamVR_Input.onSkeletonsUpdated -= SteamVR_Input_OnSkeletonsUpdated;
  292. if (skeletonAction != null)
  293. {
  294. skeletonAction.onDeviceConnectedChanged -= OnDeviceConnectedChanged;
  295. skeletonAction.onTrackingChanged -= OnTrackingChanged;
  296. }
  297. }
  298. private void OnDeviceConnectedChanged(SteamVR_Action_Skeleton fromAction, bool deviceConnected)
  299. {
  300. if (onConnectedChanged != null)
  301. onConnectedChanged.Invoke(this, inputSource, deviceConnected);
  302. if (onConnectedChangedEvent != null)
  303. onConnectedChangedEvent.Invoke(this, inputSource, deviceConnected);
  304. }
  305. private void OnTrackingChanged(SteamVR_Action_Skeleton fromAction, ETrackingResult trackingState)
  306. {
  307. if (onTrackingChanged != null)
  308. onTrackingChanged.Invoke(this, inputSource, trackingState);
  309. if (onTrackingChangedEvent != null)
  310. onTrackingChangedEvent.Invoke(this, inputSource, trackingState);
  311. }
  312. protected virtual void SteamVR_Input_OnSkeletonsUpdated(bool skipSendingEvents)
  313. {
  314. UpdateSkeleton();
  315. }
  316. protected virtual void UpdateSkeleton()
  317. {
  318. if (skeletonAction == null)
  319. return;
  320. if (updatePose)
  321. UpdatePose();
  322. if (blendPoser != null && skeletonBlend < 1)
  323. {
  324. if (blendSnapshot == null) blendSnapshot = blendPoser.GetBlendedPose(this);
  325. blendSnapshot = blendPoser.GetBlendedPose(this);
  326. }
  327. if (rangeOfMotionBlendRoutine == null)
  328. {
  329. if (temporaryRangeOfMotion != null)
  330. skeletonAction.SetRangeOfMotion(temporaryRangeOfMotion.Value);
  331. else
  332. skeletonAction.SetRangeOfMotion(rangeOfMotion); //this may be a frame behind
  333. UpdateSkeletonTransforms();
  334. }
  335. }
  336. /// <summary>
  337. /// Sets a temporary range of motion for this action that can easily be reset (using ResetTemporaryRangeOfMotion).
  338. /// This is useful for short range of motion changes, for example picking up a controller shaped object
  339. /// </summary>
  340. /// <param name="newRangeOfMotion">The new range of motion you want to apply (temporarily)</param>
  341. /// <param name="blendOverSeconds">How long you want the blend to the new range of motion to take (in seconds)</param>
  342. public void SetTemporaryRangeOfMotion(EVRSkeletalMotionRange newRangeOfMotion, float blendOverSeconds = 0.1f)
  343. {
  344. if (rangeOfMotion != newRangeOfMotion || temporaryRangeOfMotion != newRangeOfMotion)
  345. {
  346. TemporaryRangeOfMotionBlend(newRangeOfMotion, blendOverSeconds);
  347. }
  348. }
  349. /// <summary>
  350. /// Resets the previously set temporary range of motion.
  351. /// Will return to the range of motion defined by the rangeOfMotion field.
  352. /// </summary>
  353. /// <param name="blendOverSeconds">How long you want the blend to the standard range of motion to take (in seconds)</param>
  354. public void ResetTemporaryRangeOfMotion(float blendOverSeconds = 0.1f)
  355. {
  356. ResetTemporaryRangeOfMotionBlend(blendOverSeconds);
  357. }
  358. /// <summary>
  359. /// Permanently sets the range of motion for this component.
  360. /// </summary>
  361. /// <param name="newRangeOfMotion">
  362. /// The new range of motion to be set.
  363. /// WithController being the best estimation of where fingers are wrapped around the controller (pressing buttons, etc).
  364. /// WithoutController being a range between a flat hand and a fist.</param>
  365. /// <param name="blendOverSeconds">How long you want the blend to the new range of motion to take (in seconds)</param>
  366. public void SetRangeOfMotion(EVRSkeletalMotionRange newRangeOfMotion, float blendOverSeconds = 0.1f)
  367. {
  368. if (rangeOfMotion != newRangeOfMotion)
  369. {
  370. RangeOfMotionBlend(newRangeOfMotion, blendOverSeconds);
  371. }
  372. }
  373. /// <summary>
  374. /// Blend from the current skeletonBlend amount to full bone data. (skeletonBlend = 1)
  375. /// </summary>
  376. /// <param name="overTime">How long you want the blend to take (in seconds)</param>
  377. public void BlendToSkeleton(float overTime = 0.1f)
  378. {
  379. if (blendPoser != null)
  380. blendSnapshot = blendPoser.GetBlendedPose(this);
  381. blendPoser = null;
  382. BlendTo(1, overTime);
  383. }
  384. /// <summary>
  385. /// Blend from the current skeletonBlend amount to pose animation. (skeletonBlend = 0)
  386. /// Note: This will ignore the root position and rotation of the pose.
  387. /// </summary>
  388. /// <param name="overTime">How long you want the blend to take (in seconds)</param>
  389. public void BlendToPoser(SteamVR_Skeleton_Poser poser, float overTime = 0.1f)
  390. {
  391. if (poser == null)
  392. return;
  393. blendPoser = poser;
  394. BlendTo(0, overTime);
  395. }
  396. /// <summary>
  397. /// Blend from the current skeletonBlend amount to full animation data (no bone data. skeletonBlend = 0)
  398. /// </summary>
  399. /// <param name="overTime">How long you want the blend to take (in seconds)</param>
  400. public void BlendToAnimation(float overTime = 0.1f)
  401. {
  402. BlendTo(0, overTime);
  403. }
  404. /// <summary>
  405. /// Blend from the current skeletonBlend amount to a specified new amount.
  406. /// </summary>
  407. /// <param name="blendToAmount">The amount of blend you want to apply.
  408. /// 0 being fully set by animations, 1 being fully set by bone data from the action.</param>
  409. /// <param name="overTime">How long you want the blend to take (in seconds)</param>
  410. public void BlendTo(float blendToAmount, float overTime)
  411. {
  412. if (blendRoutine != null)
  413. StopCoroutine(blendRoutine);
  414. if (this.gameObject.activeInHierarchy)
  415. blendRoutine = StartCoroutine(DoBlendRoutine(blendToAmount, overTime));
  416. }
  417. protected IEnumerator DoBlendRoutine(float blendToAmount, float overTime)
  418. {
  419. float startTime = Time.time;
  420. float endTime = startTime + overTime;
  421. float startAmount = skeletonBlend;
  422. while (Time.time < endTime)
  423. {
  424. yield return null;
  425. skeletonBlend = Mathf.Lerp(startAmount, blendToAmount, (Time.time - startTime) / overTime);
  426. }
  427. skeletonBlend = blendToAmount;
  428. blendRoutine = null;
  429. }
  430. protected void RangeOfMotionBlend(EVRSkeletalMotionRange newRangeOfMotion, float blendOverSeconds)
  431. {
  432. if (rangeOfMotionBlendRoutine != null)
  433. StopCoroutine(rangeOfMotionBlendRoutine);
  434. EVRSkeletalMotionRange oldRangeOfMotion = rangeOfMotion;
  435. rangeOfMotion = newRangeOfMotion;
  436. if (this.gameObject.activeInHierarchy)
  437. {
  438. rangeOfMotionBlendRoutine = StartCoroutine(DoRangeOfMotionBlend(oldRangeOfMotion, newRangeOfMotion, blendOverSeconds));
  439. }
  440. }
  441. protected void TemporaryRangeOfMotionBlend(EVRSkeletalMotionRange newRangeOfMotion, float blendOverSeconds)
  442. {
  443. if (rangeOfMotionBlendRoutine != null)
  444. StopCoroutine(rangeOfMotionBlendRoutine);
  445. EVRSkeletalMotionRange oldRangeOfMotion = rangeOfMotion;
  446. if (temporaryRangeOfMotion != null)
  447. oldRangeOfMotion = temporaryRangeOfMotion.Value;
  448. temporaryRangeOfMotion = newRangeOfMotion;
  449. if (this.gameObject.activeInHierarchy)
  450. {
  451. rangeOfMotionBlendRoutine = StartCoroutine(DoRangeOfMotionBlend(oldRangeOfMotion, newRangeOfMotion, blendOverSeconds));
  452. }
  453. }
  454. protected void ResetTemporaryRangeOfMotionBlend(float blendOverSeconds)
  455. {
  456. if (temporaryRangeOfMotion != null)
  457. {
  458. if (rangeOfMotionBlendRoutine != null)
  459. StopCoroutine(rangeOfMotionBlendRoutine);
  460. EVRSkeletalMotionRange oldRangeOfMotion = temporaryRangeOfMotion.Value;
  461. EVRSkeletalMotionRange newRangeOfMotion = rangeOfMotion;
  462. temporaryRangeOfMotion = null;
  463. if (this.gameObject.activeInHierarchy)
  464. {
  465. rangeOfMotionBlendRoutine = StartCoroutine(DoRangeOfMotionBlend(oldRangeOfMotion, newRangeOfMotion, blendOverSeconds));
  466. }
  467. }
  468. }
  469. protected IEnumerator DoRangeOfMotionBlend(EVRSkeletalMotionRange oldRangeOfMotion, EVRSkeletalMotionRange newRangeOfMotion, float overTime)
  470. {
  471. float startTime = Time.time;
  472. float endTime = startTime + overTime;
  473. Vector3[] oldBonePositions;
  474. Quaternion[] oldBoneRotations;
  475. Vector3[] newBonePositions;
  476. Quaternion[] newBoneRotations;
  477. while (Time.time < endTime)
  478. {
  479. yield return null;
  480. float lerp = (Time.time - startTime) / overTime;
  481. if (skeletonBlend > 0)
  482. {
  483. skeletonAction.SetRangeOfMotion(oldRangeOfMotion);
  484. skeletonAction.UpdateValueWithoutEvents();
  485. oldBonePositions = (Vector3[])GetBonePositions().Clone();
  486. oldBoneRotations = (Quaternion[])GetBoneRotations().Clone();
  487. skeletonAction.SetRangeOfMotion(newRangeOfMotion);
  488. skeletonAction.UpdateValueWithoutEvents();
  489. newBonePositions = GetBonePositions();
  490. newBoneRotations = GetBoneRotations();
  491. for (int boneIndex = 0; boneIndex < bones.Length; boneIndex++)
  492. {
  493. if (bones[boneIndex] == null)
  494. continue;
  495. if (SteamVR_Utils.IsValid(newBoneRotations[boneIndex]) == false || SteamVR_Utils.IsValid(oldBoneRotations[boneIndex]) == false)
  496. {
  497. continue;
  498. }
  499. Vector3 blendedRangeOfMotionPosition = Vector3.Lerp(oldBonePositions[boneIndex], newBonePositions[boneIndex], lerp);
  500. Quaternion blendedRangeOfMotionRotation = Quaternion.Lerp(oldBoneRotations[boneIndex], newBoneRotations[boneIndex], lerp);
  501. if (skeletonBlend < 1)
  502. {
  503. if (blendPoser != null)
  504. {
  505. SetBonePosition(boneIndex, Vector3.Lerp(blendSnapshot.bonePositions[boneIndex], blendedRangeOfMotionPosition, skeletonBlend));
  506. SetBoneRotation(boneIndex, Quaternion.Lerp(GetBlendPoseForBone(boneIndex, blendedRangeOfMotionRotation), blendedRangeOfMotionRotation, skeletonBlend));
  507. }
  508. else
  509. {
  510. SetBonePosition(boneIndex, Vector3.Lerp(bones[boneIndex].localPosition, blendedRangeOfMotionPosition, skeletonBlend));
  511. SetBoneRotation(boneIndex, Quaternion.Lerp(bones[boneIndex].localRotation, blendedRangeOfMotionRotation, skeletonBlend));
  512. }
  513. }
  514. else
  515. {
  516. SetBonePosition(boneIndex, blendedRangeOfMotionPosition);
  517. SetBoneRotation(boneIndex, blendedRangeOfMotionRotation);
  518. }
  519. }
  520. }
  521. if (onBoneTransformsUpdated != null)
  522. onBoneTransformsUpdated.Invoke(this, inputSource);
  523. if (onBoneTransformsUpdatedEvent != null)
  524. onBoneTransformsUpdatedEvent.Invoke(this, inputSource);
  525. }
  526. rangeOfMotionBlendRoutine = null;
  527. }
  528. //why does this exist
  529. protected virtual Quaternion GetBlendPoseForBone(int boneIndex, Quaternion skeletonRotation)
  530. {
  531. Quaternion poseRotation = blendSnapshot.boneRotations[boneIndex];
  532. return poseRotation;
  533. }
  534. public virtual void UpdateSkeletonTransforms()
  535. {
  536. Vector3[] bonePositions = GetBonePositions();
  537. Quaternion[] boneRotations = GetBoneRotations();
  538. if (skeletonBlend <= 0)
  539. {
  540. if (blendPoser != null)
  541. {
  542. SteamVR_Skeleton_Pose_Hand mainPose = blendPoser.skeletonMainPose.GetHand(inputSource);
  543. for (int boneIndex = 0; boneIndex < bones.Length; boneIndex++)
  544. {
  545. if (bones[boneIndex] == null)
  546. continue;
  547. if ((boneIndex == SteamVR_Skeleton_JointIndexes.wrist && mainPose.ignoreWristPoseData) ||
  548. (boneIndex == SteamVR_Skeleton_JointIndexes.root && mainPose.ignoreRootPoseData))
  549. {
  550. SetBonePosition(boneIndex, bonePositions[boneIndex]);
  551. SetBoneRotation(boneIndex, boneRotations[boneIndex]);
  552. }
  553. else
  554. {
  555. Quaternion poseRotation = GetBlendPoseForBone(boneIndex, boneRotations[boneIndex]);
  556. SetBonePosition(boneIndex, blendSnapshot.bonePositions[boneIndex]);
  557. SetBoneRotation(boneIndex, poseRotation);
  558. }
  559. }
  560. }
  561. else
  562. {
  563. for (int boneIndex = 0; boneIndex < bones.Length; boneIndex++)
  564. {
  565. Quaternion poseRotation = GetBlendPoseForBone(boneIndex, boneRotations[boneIndex]);
  566. SetBonePosition(boneIndex, blendSnapshot.bonePositions[boneIndex]);
  567. SetBoneRotation(boneIndex, poseRotation);
  568. }
  569. }
  570. }
  571. else if (skeletonBlend >= 1)
  572. {
  573. for (int boneIndex = 0; boneIndex < bones.Length; boneIndex++)
  574. {
  575. if (bones[boneIndex] == null)
  576. continue;
  577. SetBonePosition(boneIndex, bonePositions[boneIndex]);
  578. SetBoneRotation(boneIndex, boneRotations[boneIndex]);
  579. }
  580. }
  581. else
  582. {
  583. for (int boneIndex = 0; boneIndex < bones.Length; boneIndex++)
  584. {
  585. if (bones[boneIndex] == null)
  586. continue;
  587. if (blendPoser != null)
  588. {
  589. SteamVR_Skeleton_Pose_Hand mainPose = blendPoser.skeletonMainPose.GetHand(inputSource);
  590. if ((boneIndex == SteamVR_Skeleton_JointIndexes.wrist && mainPose.ignoreWristPoseData) ||
  591. (boneIndex == SteamVR_Skeleton_JointIndexes.root && mainPose.ignoreRootPoseData))
  592. {
  593. SetBonePosition(boneIndex, bonePositions[boneIndex]);
  594. SetBoneRotation(boneIndex, boneRotations[boneIndex]);
  595. }
  596. else
  597. {
  598. //Quaternion poseRotation = GetBlendPoseForBone(boneIndex, boneRotations[boneIndex]);
  599. SetBonePosition(boneIndex, Vector3.Lerp(blendSnapshot.bonePositions[boneIndex], bonePositions[boneIndex], skeletonBlend));
  600. SetBoneRotation(boneIndex, Quaternion.Lerp(blendSnapshot.boneRotations[boneIndex], boneRotations[boneIndex], skeletonBlend));
  601. //SetBoneRotation(boneIndex, GetBlendPoseForBone(boneIndex, boneRotations[boneIndex]));
  602. }
  603. }
  604. else
  605. {
  606. if (blendSnapshot == null)
  607. {
  608. SetBonePosition(boneIndex, Vector3.Lerp(bones[boneIndex].localPosition, bonePositions[boneIndex], skeletonBlend));
  609. SetBoneRotation(boneIndex, Quaternion.Lerp(bones[boneIndex].localRotation, boneRotations[boneIndex], skeletonBlend));
  610. }
  611. else
  612. {
  613. SetBonePosition(boneIndex, Vector3.Lerp(blendSnapshot.bonePositions[boneIndex], bonePositions[boneIndex], skeletonBlend));
  614. SetBoneRotation(boneIndex, Quaternion.Lerp(blendSnapshot.boneRotations[boneIndex], boneRotations[boneIndex], skeletonBlend));
  615. }
  616. }
  617. }
  618. }
  619. if (onBoneTransformsUpdated != null)
  620. onBoneTransformsUpdated.Invoke(this, inputSource);
  621. if (onBoneTransformsUpdatedEvent != null)
  622. onBoneTransformsUpdatedEvent.Invoke(this, inputSource);
  623. }
  624. public virtual void SetBonePosition(int boneIndex, Vector3 localPosition)
  625. {
  626. if (onlySetRotations == false) //ignore position sets if we're only setting rotations
  627. bones[boneIndex].localPosition = localPosition;
  628. }
  629. public virtual void SetBoneRotation(int boneIndex, Quaternion localRotation)
  630. {
  631. bones[boneIndex].localRotation = localRotation;
  632. }
  633. /// <summary>
  634. /// Gets the transform for a bone by the joint index. Joint indexes specified in: SteamVR_Skeleton_JointIndexes
  635. /// </summary>
  636. /// <param name="joint">The joint index of the bone. Specified in SteamVR_Skeleton_JointIndexes</param>
  637. public virtual Transform GetBone(int joint)
  638. {
  639. if (bones == null || bones.Length == 0)
  640. Awake();
  641. return bones[joint];
  642. }
  643. /// <summary>
  644. /// Gets the position of the transform for a bone by the joint index. Joint indexes specified in: SteamVR_Skeleton_JointIndexes
  645. /// </summary>
  646. /// <param name="joint">The joint index of the bone. Specified in SteamVR_Skeleton_JointIndexes</param>
  647. /// <param name="local">true to get the localspace position for the joint (position relative to this joint's parent)</param>
  648. public Vector3 GetBonePosition(int joint, bool local = false)
  649. {
  650. if (local)
  651. return bones[joint].localPosition;
  652. else
  653. return bones[joint].position;
  654. }
  655. /// <summary>
  656. /// Gets the rotation of the transform for a bone by the joint index. Joint indexes specified in: SteamVR_Skeleton_JointIndexes
  657. /// </summary>
  658. /// <param name="joint">The joint index of the bone. Specified in SteamVR_Skeleton_JointIndexes</param>
  659. /// <param name="local">true to get the localspace rotation for the joint (rotation relative to this joint's parent)</param>
  660. public Quaternion GetBoneRotation(int joint, bool local = false)
  661. {
  662. if (local)
  663. return bones[joint].localRotation;
  664. else
  665. return bones[joint].rotation;
  666. }
  667. protected Vector3[] GetBonePositions()
  668. {
  669. if (skeletonAvailable)
  670. {
  671. Vector3[] rawSkeleton = skeletonAction.GetBonePositions();
  672. if (mirroring == MirrorType.LeftToRight || mirroring == MirrorType.RightToLeft)
  673. {
  674. for (int boneIndex = 0; boneIndex < rawSkeleton.Length; boneIndex++)
  675. {
  676. rawSkeleton[boneIndex] = MirrorPosition(boneIndex, rawSkeleton[boneIndex]);
  677. }
  678. }
  679. return rawSkeleton;
  680. }
  681. else
  682. {
  683. //fallback to getting skeleton pose from skeletonPoser
  684. if (fallbackPoser != null)
  685. {
  686. return fallbackPoser.GetBlendedPose(skeletonAction, inputSource).bonePositions;
  687. }
  688. else
  689. {
  690. Debug.LogError("Skeleton Action is not bound, and you have not provided a fallback SkeletonPoser. Please create one to drive hand animation when no skeleton data is available.", this);
  691. return null;
  692. }
  693. }
  694. }
  695. protected static readonly Quaternion rightFlipAngle = Quaternion.AngleAxis(180, Vector3.right);
  696. protected Quaternion[] GetBoneRotations()
  697. {
  698. if (skeletonAvailable)
  699. {
  700. Quaternion[] rawSkeleton = skeletonAction.GetBoneRotations();
  701. if (mirroring == MirrorType.LeftToRight || mirroring == MirrorType.RightToLeft)
  702. {
  703. for (int boneIndex = 0; boneIndex < rawSkeleton.Length; boneIndex++)
  704. {
  705. rawSkeleton[boneIndex] = MirrorRotation(boneIndex, rawSkeleton[boneIndex]);
  706. }
  707. }
  708. return rawSkeleton;
  709. }
  710. else
  711. {
  712. //fallback to getting skeleton pose from skeletonPoser
  713. if (fallbackPoser != null)
  714. {
  715. return fallbackPoser.GetBlendedPose(skeletonAction, inputSource).boneRotations;
  716. }
  717. else
  718. {
  719. Debug.LogError("Skeleton Action is not bound, and you have not provided a fallback SkeletonPoser. Please create one to drive hand animation when no skeleton data is available.", this);
  720. return null;
  721. }
  722. }
  723. }
  724. public static Vector3 MirrorPosition(int boneIndex, Vector3 rawPosition)
  725. {
  726. if (boneIndex == SteamVR_Skeleton_JointIndexes.wrist || IsMetacarpal(boneIndex))
  727. {
  728. rawPosition.Scale(new Vector3(-1, 1, 1));
  729. }
  730. else if (boneIndex != SteamVR_Skeleton_JointIndexes.root)
  731. {
  732. rawPosition = rawPosition * -1;
  733. }
  734. return rawPosition;
  735. }
  736. public static Quaternion MirrorRotation(int boneIndex, Quaternion rawRotation)
  737. {
  738. if (boneIndex == SteamVR_Skeleton_JointIndexes.wrist)
  739. {
  740. rawRotation.y = rawRotation.y * -1;
  741. rawRotation.z = rawRotation.z * -1;
  742. }
  743. if (IsMetacarpal(boneIndex))
  744. {
  745. rawRotation = rightFlipAngle * rawRotation;
  746. }
  747. return rawRotation;
  748. }
  749. protected virtual void UpdatePose()
  750. {
  751. if (skeletonAction == null)
  752. return;
  753. Vector3 skeletonPosition = skeletonAction.GetLocalPosition();
  754. Quaternion skeletonRotation = skeletonAction.GetLocalRotation();
  755. if (origin == null)
  756. {
  757. if (this.transform.parent != null)
  758. {
  759. skeletonPosition = this.transform.parent.TransformPoint(skeletonPosition);
  760. skeletonRotation = this.transform.parent.rotation * skeletonRotation;
  761. }
  762. }
  763. else
  764. {
  765. skeletonPosition = origin.TransformPoint(skeletonPosition);
  766. skeletonRotation = origin.rotation * skeletonRotation;
  767. }
  768. if (skeletonAction.poseChanged)
  769. {
  770. if (onTransformChanged != null)
  771. onTransformChanged.Invoke(this, inputSource);
  772. if (onTransformChangedEvent != null)
  773. onTransformChangedEvent.Invoke(this, inputSource);
  774. }
  775. this.transform.position = skeletonPosition;
  776. this.transform.rotation = skeletonRotation;
  777. if (onTransformUpdated != null)
  778. onTransformUpdated.Invoke(this, inputSource);
  779. }
  780. /// <summary>
  781. /// Returns an array of positions/rotations that represent the state of each bone in a reference pose.
  782. /// </summary>
  783. /// <param name="referencePose">Which reference pose to return</param>
  784. public void ForceToReferencePose(EVRSkeletalReferencePose referencePose)
  785. {
  786. bool temporarySession = false;
  787. if (Application.isEditor && Application.isPlaying == false)
  788. {
  789. temporarySession = SteamVR.InitializeTemporarySession(true);
  790. Awake();
  791. #if UNITY_EDITOR
  792. //gotta wait a bit for steamvr input to startup //todo: implement steamvr_input.isready
  793. string title = "SteamVR";
  794. string text = "Getting reference pose...";
  795. float msToWait = 3000;
  796. float increment = 100;
  797. for (float timer = 0; timer < msToWait; timer += increment)
  798. {
  799. bool cancel = UnityEditor.EditorUtility.DisplayCancelableProgressBar(title, text, timer / msToWait);
  800. if (cancel)
  801. {
  802. UnityEditor.EditorUtility.ClearProgressBar();
  803. if (temporarySession)
  804. SteamVR.ExitTemporarySession();
  805. return;
  806. }
  807. System.Threading.Thread.Sleep((int)increment);
  808. }
  809. UnityEditor.EditorUtility.ClearProgressBar();
  810. #endif
  811. skeletonAction.actionSet.Activate();
  812. SteamVR_ActionSet_Manager.UpdateActionStates(true);
  813. skeletonAction.UpdateValueWithoutEvents();
  814. }
  815. if (skeletonAction.active == false)
  816. {
  817. Debug.LogError("<b>[SteamVR Input]</b> Please turn on your " + inputSource.ToString() + " controller and ensure SteamVR is open.", this);
  818. return;
  819. }
  820. SteamVR_Utils.RigidTransform[] transforms = skeletonAction.GetReferenceTransforms(EVRSkeletalTransformSpace.Parent, referencePose);
  821. if (transforms == null || transforms.Length == 0)
  822. {
  823. 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.", this);
  824. }
  825. if (mirroring == MirrorType.LeftToRight || mirroring == MirrorType.RightToLeft)
  826. {
  827. for (int boneIndex = 0; boneIndex < transforms.Length; boneIndex++)
  828. {
  829. bones[boneIndex].localPosition = MirrorPosition(boneIndex, transforms[boneIndex].pos);
  830. bones[boneIndex].localRotation = MirrorRotation(boneIndex, transforms[boneIndex].rot);
  831. }
  832. }
  833. else
  834. {
  835. for (int boneIndex = 0; boneIndex < transforms.Length; boneIndex++)
  836. {
  837. bones[boneIndex].localPosition = transforms[boneIndex].pos;
  838. bones[boneIndex].localRotation = transforms[boneIndex].rot;
  839. }
  840. }
  841. if (temporarySession)
  842. SteamVR.ExitTemporarySession();
  843. }
  844. protected static bool IsMetacarpal(int boneIndex)
  845. {
  846. return (boneIndex == SteamVR_Skeleton_JointIndexes.indexMetacarpal ||
  847. boneIndex == SteamVR_Skeleton_JointIndexes.middleMetacarpal ||
  848. boneIndex == SteamVR_Skeleton_JointIndexes.ringMetacarpal ||
  849. boneIndex == SteamVR_Skeleton_JointIndexes.pinkyMetacarpal ||
  850. boneIndex == SteamVR_Skeleton_JointIndexes.thumbMetacarpal);
  851. }
  852. public enum MirrorType
  853. {
  854. None,
  855. LeftToRight,
  856. RightToLeft
  857. }
  858. public delegate void ActiveChangeHandler(SteamVR_Behaviour_Skeleton fromAction, SteamVR_Input_Sources inputSource, bool active);
  859. public delegate void ChangeHandler(SteamVR_Behaviour_Skeleton fromAction, SteamVR_Input_Sources inputSource);
  860. public delegate void UpdateHandler(SteamVR_Behaviour_Skeleton fromAction, SteamVR_Input_Sources inputSource);
  861. public delegate void TrackingChangeHandler(SteamVR_Behaviour_Skeleton fromAction, SteamVR_Input_Sources inputSource, ETrackingResult trackingState);
  862. public delegate void ValidPoseChangeHandler(SteamVR_Behaviour_Skeleton fromAction, SteamVR_Input_Sources inputSource, bool validPose);
  863. public delegate void DeviceConnectedChangeHandler(SteamVR_Behaviour_Skeleton fromAction, SteamVR_Input_Sources inputSource, bool deviceConnected);
  864. }
  865. }