luminance_reduce.glsl 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #[compute]
  2. #version 450
  3. #VERSION_DEFINES
  4. #define BLOCK_SIZE 8
  5. layout(local_size_x = BLOCK_SIZE, local_size_y = BLOCK_SIZE, local_size_z = 1) in;
  6. shared float tmp_data[BLOCK_SIZE * BLOCK_SIZE];
  7. #ifdef READ_TEXTURE
  8. //use for main texture
  9. layout(set = 0, binding = 0) uniform sampler2D source_texture;
  10. #else
  11. //use for intermediate textures
  12. layout(r32f, set = 0, binding = 0) uniform restrict readonly image2D source_luminance;
  13. #endif
  14. layout(r32f, set = 1, binding = 0) uniform restrict writeonly image2D dest_luminance;
  15. #ifdef WRITE_LUMINANCE
  16. layout(set = 2, binding = 0) uniform sampler2D prev_luminance;
  17. #endif
  18. layout(push_constant, std430) uniform Params {
  19. ivec2 source_size;
  20. float max_luminance;
  21. float min_luminance;
  22. float exposure_adjust;
  23. float pad[3];
  24. }
  25. params;
  26. void main() {
  27. uint t = gl_LocalInvocationID.y * BLOCK_SIZE + gl_LocalInvocationID.x;
  28. ivec2 pos = ivec2(gl_GlobalInvocationID.xy);
  29. if (any(lessThan(pos, params.source_size))) {
  30. #ifdef READ_TEXTURE
  31. vec3 v = texelFetch(source_texture, pos, 0).rgb;
  32. tmp_data[t] = max(v.r, max(v.g, v.b));
  33. #else
  34. tmp_data[t] = imageLoad(source_luminance, pos).r;
  35. #endif
  36. } else {
  37. tmp_data[t] = 0.0;
  38. }
  39. groupMemoryBarrier();
  40. barrier();
  41. uint size = (BLOCK_SIZE * BLOCK_SIZE) >> 1;
  42. do {
  43. if (t < size) {
  44. tmp_data[t] += tmp_data[t + size];
  45. }
  46. groupMemoryBarrier();
  47. barrier();
  48. size >>= 1;
  49. } while (size >= 1);
  50. if (t == 0) {
  51. //compute rect size
  52. ivec2 rect_size = min(params.source_size - pos, ivec2(BLOCK_SIZE));
  53. float avg = tmp_data[0] / float(rect_size.x * rect_size.y);
  54. //float avg = tmp_data[0] / float(BLOCK_SIZE*BLOCK_SIZE);
  55. pos /= ivec2(BLOCK_SIZE);
  56. #ifdef WRITE_LUMINANCE
  57. float prev_lum = texelFetch(prev_luminance, ivec2(0, 0), 0).r; //1 pixel previous exposure
  58. avg = clamp(prev_lum + (avg - prev_lum) * params.exposure_adjust, params.min_luminance, params.max_luminance);
  59. #endif
  60. imageStore(dest_luminance, pos, vec4(avg));
  61. }
  62. }