MaterialBlitRenderPass.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using UnityEngine;
  2. using UnityEngine.Rendering;
  3. using UnityEngine.Rendering.Universal;
  4. namespace SicknessReduction.Visual.Rendering
  5. {
  6. internal class MaterialBlitRenderPass : ScriptableRenderPass
  7. {
  8. private RenderTargetIdentifier cameraColorTargetIdent;
  9. private readonly Material materialToBlit;
  10. // used to label this pass in Unity's Frame Debug utility
  11. private readonly string profilerTag;
  12. private RenderTargetHandle tempTexture;
  13. public MaterialBlitRenderPass(string profilerTag,
  14. RenderPassEvent renderPassEvent, Material materialToBlit)
  15. {
  16. this.profilerTag = profilerTag;
  17. this.renderPassEvent = renderPassEvent;
  18. this.materialToBlit = materialToBlit;
  19. }
  20. // This isn't part of the ScriptableRenderPass class and is our own addition.
  21. // For this custom pass we need the camera's color target, so that gets passed in.
  22. public void Setup(RenderTargetIdentifier cameraColorTargetIdent)
  23. {
  24. this.cameraColorTargetIdent = cameraColorTargetIdent;
  25. }
  26. // called each frame before Execute, use it to set up things the pass will need
  27. public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
  28. {
  29. // create a temporary render texture that matches the camera
  30. cmd.GetTemporaryRT(tempTexture.id, cameraTextureDescriptor);
  31. }
  32. // Execute is called for every eligible camera every frame. It's not called at the moment that
  33. // rendering is actually taking place, so don't directly execute rendering commands here.
  34. // Instead use the methods on ScriptableRenderContext to set up instructions.
  35. // RenderingData provides a bunch of (not very well documented) information about the scene
  36. // and what's being rendered.
  37. public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
  38. {
  39. // fetch a command buffer to use
  40. var cmd = CommandBufferPool.Get(profilerTag);
  41. cmd.Clear();
  42. // the actual content of our custom render pass!
  43. // we apply our material while blitting to a temporary texture
  44. cmd.Blit(cameraColorTargetIdent, tempTexture.Identifier(), materialToBlit, 0);
  45. // ...then blit it back again
  46. cmd.Blit(tempTexture.Identifier(), cameraColorTargetIdent);
  47. // don't forget to tell ScriptableRenderContext to actually execute the commands
  48. context.ExecuteCommandBuffer(cmd);
  49. // tidy up after ourselves
  50. cmd.Clear();
  51. CommandBufferPool.Release(cmd);
  52. }
  53. // called after Execute, use it to clean up anything allocated in Configure
  54. public override void FrameCleanup(CommandBuffer cmd)
  55. {
  56. cmd.ReleaseTemporaryRT(tempTexture.id);
  57. }
  58. }
  59. }