DrawOutputToPlane.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. #if ZED_HDRP || ZED_URP
  5. using UnityEngine.Rendering;
  6. #endif
  7. /// <summary>
  8. /// Copies an attached camera's output to a target RenderTexture each frame.
  9. /// Also includes an option to pause this.
  10. /// </summary><remarks>The pause feature is not used in the MR calibration scene.</remarks>
  11. [RequireComponent(typeof(Camera))]
  12. public class DrawOutputToPlane : MonoBehaviour
  13. {
  14. /// <summary>
  15. /// Intermediary texture we copy to when unpaused, which we also set as the target Renderer's main texture.
  16. /// </summary>
  17. private RenderTexture targetTexture;
  18. /// <summary>
  19. /// Texture applied to the final material.
  20. /// </summary>
  21. private RenderTexture outputTexture;
  22. /// <summary>
  23. /// Renderer onto whose material this class will copy the camera's output.
  24. /// </summary>
  25. public MeshRenderer outputRenderer;
  26. /// <summary>
  27. /// Set to true to pause the updates, leaving the texture to show the last rendered frame until unpaused.
  28. /// </summary>
  29. public static bool pauseTextureUpdate = false;
  30. private void Awake()
  31. {
  32. Camera cam = GetComponent<Camera>();
  33. targetTexture = new RenderTexture(cam.pixelWidth, cam.pixelHeight, 0);
  34. targetTexture.Create();
  35. outputTexture = new RenderTexture(targetTexture);
  36. outputTexture.Create();
  37. cam.targetTexture = targetTexture;
  38. if (outputRenderer) outputRenderer.material.SetTexture("_MainTex", outputTexture); //TODO: Cache shader ID.
  39. // (targetRenderer) targetRenderer.material.mainTexture = targetTexture;
  40. #if ZED_HDRP || ZED_URP
  41. RenderPipelineManager.endFrameRendering += OnFrameEnd;
  42. if (outputRenderer) outputRenderer.material.mainTexture = targetTexture;
  43. #endif
  44. }
  45. #if ZED_HDRP || ZED_URP
  46. /// <summary>
  47. /// Blits the intermediary targetTexture to the final outputTexture for rendering. Used in SRP because there is no OnRenderImage automatic function.
  48. /// </summary>
  49. private void OnFrameEnd(ScriptableRenderContext context, Camera[] cams)
  50. {
  51. if (targetTexture != null && pauseTextureUpdate != true)
  52. {
  53. Graphics.Blit(targetTexture, outputTexture);
  54. }
  55. }
  56. #endif
  57. /// <summary>
  58. /// Copies the output to the intermediary texture whenever the attached camera renders.
  59. /// </summary>
  60. private void OnRenderImage(RenderTexture source, RenderTexture destination)
  61. {
  62. if (targetTexture != null && pauseTextureUpdate != true)
  63. {
  64. Graphics.Blit(source, outputTexture);
  65. }
  66. }
  67. }