blur.fs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #version 300 es
  2. precision highp float;
  3. in vec2 fragTexCoord;
  4. uniform sampler2D gbufferNormal;
  5. uniform sampler2D gbufferDepth;
  6. uniform sampler2D inputTexture;
  7. uniform mat4 camInvProj;
  8. uniform float camClipNear;
  9. uniform float camClipFar;
  10. uniform vec2 invTextureResolution;
  11. uniform vec2 blurDirection;
  12. float NonlinearDepth(float depth, float near, float far)
  13. {
  14. return (((2.0 * near) / depth) - far - near) / (near - far);
  15. }
  16. vec3 CameraSpace(vec2 texcoord, float depth)
  17. {
  18. vec4 positionClip = vec4(vec3(texcoord, NonlinearDepth(depth, camClipNear, camClipFar)) * 2.0 - 1.0, 1.0);
  19. vec4 position = camInvProj * positionClip;
  20. return position.xyz / position.w;
  21. }
  22. float FastNegExp(float x)
  23. {
  24. return 1.0f / (1.0f + x + 0.48f*x*x + 0.235f*x*x*x);
  25. }
  26. out vec4 finalColor;
  27. void main()
  28. {
  29. float depth = texture(gbufferDepth, fragTexCoord).r;
  30. if (depth == 1.0f) { discard; }
  31. vec3 baseNormal = texture(gbufferNormal, fragTexCoord).rgb * 2.0f - 1.0f;
  32. vec3 basePosition = CameraSpace(fragTexCoord, depth);
  33. vec4 totalColor = vec4(0.0f, 0.0f, 0.0f, 0.0f);
  34. float totalWeight = 0.0f;
  35. float stride = 2.0f;
  36. for (int x = -3; x <= 3; x++)
  37. {
  38. vec2 sampleTexcoord = fragTexCoord + float(x) * stride * blurDirection * invTextureResolution;
  39. vec4 sampleColour = texture(inputTexture, sampleTexcoord);
  40. vec3 sampleNormal = texture(gbufferNormal, sampleTexcoord).rgb * 2.0f - 1.0f;
  41. vec3 samplePosition = CameraSpace(sampleTexcoord, texture(gbufferDepth, sampleTexcoord).r);
  42. vec3 diffPosition = (samplePosition - basePosition) / 0.05f;
  43. float weightPosition = FastNegExp(dot(diffPosition, diffPosition));
  44. float weightNormal = max(dot(sampleNormal, baseNormal), 0.0f);
  45. float weight = weightPosition * weightNormal;
  46. totalColor += weight * sampleColour;
  47. totalWeight += weight;
  48. }
  49. finalColor = totalColor / totalWeight;
  50. //finalColor = texture(inputTexture, fragTexCoord);
  51. }