Tonemapping.glsl 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright (C) 2009-2018, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #ifndef ANKI_SHADERS_TONEMAP_GLSL
  6. #define ANKI_SHADERS_TONEMAP_GLSL
  7. #include "shaders/Common.glsl"
  8. // A tick to compute log of base 10
  9. float log10(in float x)
  10. {
  11. return log(x) / log(10.0);
  12. }
  13. float computeLuminance(in vec3 color)
  14. {
  15. return max(dot(vec3(0.30, 0.59, 0.11), color), EPSILON);
  16. }
  17. float computeExposure(float avgLum, float threshold)
  18. {
  19. float keyValue = 1.03 - (2.0 / (2.0 + log10(avgLum + 1.0)));
  20. float linearExposure = (keyValue / avgLum);
  21. float exposure = log2(linearExposure);
  22. exposure -= threshold;
  23. return exp2(exposure);
  24. }
  25. vec3 computeExposedColor(in vec3 color, in float avgLum, in float threshold)
  26. {
  27. return computeExposure(avgLum, threshold) * color;
  28. }
  29. // Reinhard operator
  30. vec3 tonemapReinhard(in vec3 color, in float saturation)
  31. {
  32. float lum = computeLuminance(color);
  33. float toneMappedLuminance = lum / (lum + 1.0);
  34. return toneMappedLuminance * pow(color / lum, vec3(saturation));
  35. }
  36. // Uncharted 2 operator
  37. vec3 tonemapUncharted2(in vec3 color)
  38. {
  39. const float A = 0.15;
  40. const float B = 0.50;
  41. const float C = 0.10;
  42. const float D = 0.20;
  43. const float E = 0.02;
  44. const float F = 0.30;
  45. return ((color * (A * color + C * B) + D * E) / (color * (A * color + B) + D * F)) - E / F;
  46. }
  47. vec3 tonemap(vec3 color, float exposure)
  48. {
  49. color *= exposure;
  50. float saturation = 1.0;
  51. return tonemapReinhard(color, saturation);
  52. }
  53. vec3 tonemap(vec3 color, float avgLum, float threshold)
  54. {
  55. float exposure = computeExposure(avgLum, threshold);
  56. return tonemap(color, exposure);
  57. }
  58. #endif