DitheringComponent.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. namespace UnityEngine.PostProcessing
  2. {
  3. public sealed class DitheringComponent : PostProcessingComponentRenderTexture<DitheringModel>
  4. {
  5. static class Uniforms
  6. {
  7. internal static readonly int _DitheringTex = Shader.PropertyToID("_DitheringTex");
  8. internal static readonly int _DitheringCoords = Shader.PropertyToID("_DitheringCoords");
  9. }
  10. public override bool active
  11. {
  12. get
  13. {
  14. return model.enabled
  15. && !context.interrupted;
  16. }
  17. }
  18. // Holds 64 64x64 Alpha8 textures (256kb total)
  19. Texture2D[] noiseTextures;
  20. int textureIndex = 0;
  21. const int k_TextureCount = 64;
  22. public override void OnDisable()
  23. {
  24. noiseTextures = null;
  25. }
  26. void LoadNoiseTextures()
  27. {
  28. noiseTextures = new Texture2D[k_TextureCount];
  29. for (int i = 0; i < k_TextureCount; i++)
  30. noiseTextures[i] = Resources.Load<Texture2D>("Bluenoise64/LDR_LLL1_" + i);
  31. }
  32. public override void Prepare(Material uberMaterial)
  33. {
  34. float rndOffsetX;
  35. float rndOffsetY;
  36. #if POSTFX_DEBUG_STATIC_DITHERING
  37. textureIndex = 0;
  38. rndOffsetX = 0f;
  39. rndOffsetY = 0f;
  40. #else
  41. if (++textureIndex >= k_TextureCount)
  42. textureIndex = 0;
  43. rndOffsetX = Random.value;
  44. rndOffsetY = Random.value;
  45. #endif
  46. if (noiseTextures == null)
  47. LoadNoiseTextures();
  48. var noiseTex = noiseTextures[textureIndex];
  49. uberMaterial.EnableKeyword("DITHERING");
  50. uberMaterial.SetTexture(Uniforms._DitheringTex, noiseTex);
  51. uberMaterial.SetVector(Uniforms._DitheringCoords, new Vector4(
  52. (float)context.width / (float)noiseTex.width,
  53. (float)context.height / (float)noiseTex.height,
  54. rndOffsetX,
  55. rndOffsetY
  56. ));
  57. }
  58. }
  59. }