GrainComponent.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. namespace UnityEngine.PostProcessing
  2. {
  3. public sealed class GrainComponent : PostProcessingComponentRenderTexture<GrainModel>
  4. {
  5. static class Uniforms
  6. {
  7. internal static readonly int _Grain_Params1 = Shader.PropertyToID("_Grain_Params1");
  8. internal static readonly int _Grain_Params2 = Shader.PropertyToID("_Grain_Params2");
  9. internal static readonly int _GrainTex = Shader.PropertyToID("_GrainTex");
  10. internal static readonly int _Phase = Shader.PropertyToID("_Phase");
  11. }
  12. public override bool active
  13. {
  14. get
  15. {
  16. return model.enabled
  17. && model.settings.intensity > 0f
  18. && SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf)
  19. && !context.interrupted;
  20. }
  21. }
  22. RenderTexture m_GrainLookupRT;
  23. public override void OnDisable()
  24. {
  25. GraphicsUtils.Destroy(m_GrainLookupRT);
  26. m_GrainLookupRT = null;
  27. }
  28. public override void Prepare(Material uberMaterial)
  29. {
  30. var settings = model.settings;
  31. uberMaterial.EnableKeyword("GRAIN");
  32. float rndOffsetX;
  33. float rndOffsetY;
  34. #if POSTFX_DEBUG_STATIC_GRAIN
  35. // Chosen by a fair dice roll
  36. float time = 4f;
  37. rndOffsetX = 0f;
  38. rndOffsetY = 0f;
  39. #else
  40. float time = Time.realtimeSinceStartup;
  41. rndOffsetX = Random.value;
  42. rndOffsetY = Random.value;
  43. #endif
  44. // Generate the grain lut for the current frame first
  45. if (m_GrainLookupRT == null || !m_GrainLookupRT.IsCreated())
  46. {
  47. GraphicsUtils.Destroy(m_GrainLookupRT);
  48. m_GrainLookupRT = new RenderTexture(192, 192, 0, RenderTextureFormat.ARGBHalf)
  49. {
  50. filterMode = FilterMode.Bilinear,
  51. wrapMode = TextureWrapMode.Repeat,
  52. anisoLevel = 0,
  53. name = "Grain Lookup Texture"
  54. };
  55. m_GrainLookupRT.Create();
  56. }
  57. var grainMaterial = context.materialFactory.Get("Hidden/Post FX/Grain Generator");
  58. grainMaterial.SetFloat(Uniforms._Phase, time / 20f);
  59. Graphics.Blit((Texture)null, m_GrainLookupRT, grainMaterial, settings.colored ? 1 : 0);
  60. // Send everything to the uber shader
  61. uberMaterial.SetTexture(Uniforms._GrainTex, m_GrainLookupRT);
  62. uberMaterial.SetVector(Uniforms._Grain_Params1, new Vector2(settings.luminanceContribution, settings.intensity * 20f));
  63. uberMaterial.SetVector(Uniforms._Grain_Params2, new Vector4((float)context.width / (float)m_GrainLookupRT.width / settings.size, (float)context.height / (float)m_GrainLookupRT.height / settings.size, rndOffsetX, rndOffsetY));
  64. }
  65. }
  66. }