MotionBlur.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using UnityEngine;
  3. // This class implements simple ghosting type Motion Blur.
  4. // If Extra Blur is selected, the scene will allways be a little blurred,
  5. // as it is scaled to a smaller resolution.
  6. // The effect works by accumulating the previous frames in an accumulation
  7. // texture.
  8. namespace UnityStandardAssets.ImageEffects
  9. {
  10. [ExecuteInEditMode]
  11. [AddComponentMenu("Image Effects/Blur/Motion Blur (Color Accumulation)")]
  12. [RequireComponent(typeof(Camera))]
  13. public class MotionBlur : ImageEffectBase
  14. {
  15. [Range(0.0f, 0.92f)]
  16. public float blurAmount = 0.8f;
  17. public bool extraBlur = false;
  18. private RenderTexture accumTexture;
  19. override protected void Start()
  20. {
  21. if (!SystemInfo.supportsRenderTextures)
  22. {
  23. enabled = false;
  24. return;
  25. }
  26. base.Start();
  27. }
  28. override protected void OnDisable()
  29. {
  30. base.OnDisable();
  31. DestroyImmediate(accumTexture);
  32. }
  33. // Called by camera to apply image effect
  34. void OnRenderImage (RenderTexture source, RenderTexture destination)
  35. {
  36. // Create the accumulation texture
  37. if (accumTexture == null || accumTexture.width != source.width || accumTexture.height != source.height)
  38. {
  39. DestroyImmediate(accumTexture);
  40. accumTexture = new RenderTexture(source.width, source.height, 0);
  41. accumTexture.hideFlags = HideFlags.HideAndDontSave;
  42. Graphics.Blit( source, accumTexture );
  43. }
  44. // If Extra Blur is selected, downscale the texture to 4x4 smaller resolution.
  45. if (extraBlur)
  46. {
  47. RenderTexture blurbuffer = RenderTexture.GetTemporary(source.width/4, source.height/4, 0);
  48. accumTexture.MarkRestoreExpected();
  49. Graphics.Blit(accumTexture, blurbuffer);
  50. Graphics.Blit(blurbuffer,accumTexture);
  51. RenderTexture.ReleaseTemporary(blurbuffer);
  52. }
  53. // Clamp the motion blur variable, so it can never leave permanent trails in the image
  54. blurAmount = Mathf.Clamp( blurAmount, 0.0f, 0.92f );
  55. // Setup the texture and floating point values in the shader
  56. material.SetTexture("_MainTex", accumTexture);
  57. material.SetFloat("_AccumOrig", 1.0F-blurAmount);
  58. // We are accumulating motion over frames without clear/discard
  59. // by design, so silence any performance warnings from Unity
  60. accumTexture.MarkRestoreExpected();
  61. // Render the image using the motion blur shader
  62. Graphics.Blit (source, accumTexture, material);
  63. Graphics.Blit (accumTexture, destination);
  64. }
  65. }
  66. }