Adaptation.shader 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Calculates adaptation to minimum/maximum luminance values,
  2. // based on "currently adapted" and "new values to adapt to"
  3. // textures (both 1x1).
  4. Shader "Hidden/Contrast Stretch Adaptation" {
  5. Properties {
  6. _MainTex ("Base (RGB)", 2D) = "white" {}
  7. _CurTex ("Base (RGB)", 2D) = "white" {}
  8. }
  9. Category {
  10. SubShader {
  11. Pass {
  12. ZTest Always Cull Off ZWrite Off
  13. CGPROGRAM
  14. #pragma vertex vert_img
  15. #pragma fragment frag
  16. #include "UnityCG.cginc"
  17. uniform sampler2D _MainTex; // currently adapted to
  18. uniform sampler2D _CurTex; // new value to adapt to
  19. uniform float4 _AdaptParams; // x=adaptLerp, y=limitMinimum, z=limitMaximum
  20. float4 frag (v2f_img i) : SV_Target {
  21. // value is: max, min
  22. float2 valAdapted = tex2D(_MainTex, i.uv).xy;
  23. float2 valCur = tex2D(_CurTex, i.uv).xy;
  24. // Calculate new adapted values: interpolate
  25. // from valAdapted to valCur by script-supplied amount.
  26. //
  27. // Because we store adaptation levels in a simple 8 bit/channel
  28. // texture, we might not have enough precision - the interpolation
  29. // amount might be too small to change anything, and we'll never
  30. // arrive at the needed values.
  31. //
  32. // So we make sure the change we do is at least 1/255th of the
  33. // color range - this way we'll always change the value.
  34. const float kMinChange = 1.0/255.0;
  35. float2 delta = (valCur-valAdapted) * _AdaptParams.x;
  36. delta.x = sign(delta.x) * max( kMinChange, abs(delta.x) );
  37. delta.y = sign(delta.y) * max( kMinChange, abs(delta.y) );
  38. float4 valNew;
  39. valNew.xy = valAdapted + delta;
  40. // Impose user limits on maximum/minimum values
  41. valNew.x = max( valNew.x, _AdaptParams.z );
  42. valNew.y = min( valNew.y, _AdaptParams.y );
  43. // Optimization so that our final apply pass is faster:
  44. // z = max-min (plus a small amount to prevent division by zero)
  45. valNew.z = valNew.x - valNew.y + 0.01;
  46. // w = min/(max-min)
  47. valNew.w = valNew.y / valNew.z;
  48. return valNew;
  49. }
  50. ENDCG
  51. }
  52. }
  53. }
  54. Fallback off
  55. }