SteamVR_TestTrackedCamera.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //======= Copyright (c) Valve Corporation, All rights reserved. ===============
  2. using UnityEngine;
  3. public class SteamVR_TestTrackedCamera : MonoBehaviour
  4. {
  5. public Material material;
  6. public Transform target;
  7. public bool undistorted = true;
  8. public bool cropped = true;
  9. void OnEnable()
  10. {
  11. // The video stream must be symmetrically acquired and released in
  12. // order to properly disable the stream once there are no consumers.
  13. var source = SteamVR_TrackedCamera.Source(undistorted);
  14. source.Acquire();
  15. // Auto-disable if no camera is present.
  16. if (!source.hasCamera)
  17. enabled = false;
  18. }
  19. void OnDisable()
  20. {
  21. // Clear the texture when no longer active.
  22. material.mainTexture = null;
  23. // The video stream must be symmetrically acquired and released in
  24. // order to properly disable the stream once there are no consumers.
  25. var source = SteamVR_TrackedCamera.Source(undistorted);
  26. source.Release();
  27. }
  28. void Update()
  29. {
  30. var source = SteamVR_TrackedCamera.Source(undistorted);
  31. var texture = source.texture;
  32. if (texture == null)
  33. {
  34. return;
  35. }
  36. // Apply the latest texture to the material. This must be performed
  37. // every frame since the underlying texture is actually part of a ring
  38. // buffer which is updated in lock-step with its associated pose.
  39. // (You actually really only need to call any of the accessors which
  40. // internally call Update on the SteamVR_TrackedCamera.VideoStreamTexture).
  41. material.mainTexture = texture;
  42. // Adjust the height of the quad based on the aspect to keep the texels square.
  43. var aspect = (float)texture.width / texture.height;
  44. // The undistorted video feed has 'bad' areas near the edges where the original
  45. // square texture feed is stretched to undo the fisheye from the lens.
  46. // Therefore, you'll want to crop it to the specified frameBounds to remove this.
  47. if (cropped)
  48. {
  49. var bounds = source.frameBounds;
  50. material.mainTextureOffset = new Vector2(bounds.uMin, bounds.vMin);
  51. var du = bounds.uMax - bounds.uMin;
  52. var dv = bounds.vMax - bounds.vMin;
  53. material.mainTextureScale = new Vector2(du, dv);
  54. aspect *= Mathf.Abs(du / dv);
  55. }
  56. else
  57. {
  58. material.mainTextureOffset = Vector2.zero;
  59. material.mainTextureScale = new Vector2(1, -1);
  60. }
  61. target.localScale = new Vector3(1, 1.0f / aspect, 1);
  62. // Apply the pose that this frame was recorded at.
  63. if (source.hasTracking)
  64. {
  65. var t = source.transform;
  66. target.localPosition = t.pos;
  67. target.localRotation = t.rot;
  68. }
  69. }
  70. }